I had four tabs in my view and the tab output depend on other tab input in same view. So when I click on one tab, it generates an array list and show item in list view but when second time I click on the same tab it gives array index out of bound exception. I think it is because of previous downloaded content was in the view so how to remove/delete previous loaded content when I clicked first time on tab. I know it can be done onresume() and onpause() method but what code should be in onpause() for removing previous loaded content. For refreshing it with new content. ontabclick().
Thanks!
public class OpeningToday extends ListActivity {
String name = null;
String typename = null;
static String array_type[];
static int totalartist;
static String array_galleryname[]=null;
static String array_address[]=null;
static String array_galleryurl[]=null;
static String array_email[];
static String array_web[];
static String array_phone[];
static String array_latitude[];
static String array_longitude[];
SitesList2 sitesList;
//static String gallerynames;
//static String addresses;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("saurabh trivedi","saurabh trivedui");
super.onCreate(savedInstanceState);
setContentView(R.layout.openingtoday);
ImageView iv=(ImageView)findViewById(R.id.imv);
iv.setBackgroundResource(R.drawable.fiiatlogo);
new ProgressTask6().execute();
}
protected void onPause() {
super.onPause();
}
protected void onResume()
{
super.onResume();
new ProgressTask6().execute();
}
private class ProgressTask6 extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Context context;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OpeningToday.this);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing())
{
dialog.dismiss();
setListAdapter(new MyAdapter(OpeningToday.this));
}
if(totalartist==0)
{
AlertDialog.Builder alt_bld = new AlertDialog.Builder(OpeningToday.this);
alt_bld.setMessage("galleries not found..")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Title");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
#Override
protected Boolean doInBackground(String... args) {
try{
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
String temp = "http://www.arteonline.mobi/iphone/output.php?visit=1";
temp = temp.replaceAll(" " ,"%20");
Log.i("temp url..",temp);
URL sourceUrl = new URL(temp);
XMLHandler myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
sitesList = XMLHandler.sitesList2;
keywordresulttab.array_galleryname = new String[sitesList.getGalleryname().size()];
totalartist= sitesList.getGalleryname().size();
Log.i("opening today artist..",Integer.toString(totalartist));
for (int i = 0; i < sitesList.getGalleryname().size(); i++)
{
name = sitesList.getGalleryname().get(i);
keywordresulttab.array_galleryname[i] = name;
// Log.i("array_spinner" + i, array_galleryname[i]);
}
keywordresulttab.array_type = new String[sitesList.getType().size()];
for (int i = 0; i < sitesList.getType().size(); i++)
{
name = sitesList.getType().get(i);
keywordresulttab.array_type[i] = name;
// Log.i("array_spinner" + i, array_estado[i]);
}
keywordresulttab.array_email = new String[sitesList.getEmail().size()];
for (int i = 0; i < sitesList.getEmail().size(); i++)
{
name = sitesList.getType().get(i);
keywordresulttab.array_email[i] = name;
// Log.i("array_spinner" + i, array_estado[i]);
}
keywordresulttab.array_address = new String[sitesList.getAddress().size()];
for (int i = 0; i < sitesList.getAddress().size(); i++)
{
name = sitesList.getAddress().get(i);
keywordresulttab.array_address[i] = name;
//Log.i("array_spinner" + i, array_address[i]);
}
keywordresulttab.array_web = new String[sitesList.getWeb().size()];
for (int i = 0; i < sitesList.getWeb().size(); i++)
{
name = sitesList.getWeb().get(i);
keywordresulttab.array_web[i] = name;
}
keywordresulttab.array_lati = new String[sitesList.getLati().size()];
for (int i = 0; i < sitesList.getLati().size(); i++)
{
name = sitesList.getLati().get(i);
keywordresulttab.array_lati[i] = name;
Log.i("array_spinner" + i,keywordresulttab.array_lati[i]);
}
keywordresulttab.array_longi = new String[sitesList.getLongi().size()];
for (int i = 0; i < sitesList.getLongi().size(); i++)
{
name = sitesList.getLongi().get(i);
keywordresulttab.array_longi[i] = name;
Log.i("array_spinner" + i, keywordresulttab.array_longi[i]);
}
keywordresulttab.array_phone = new String[sitesList.getPhoneno().size()];
for (int i = 0; i < sitesList.getPhoneno().size(); i++)
{
name = sitesList.getPhoneno().get(i);
keywordresulttab.array_phone[i] = name;
}
keywordresulttab.array_imgurl = new String[sitesList.getImagegalleryurl().size()];
for (int i = 0; i < sitesList.getImagegalleryurl().size(); i++)
{
name = sitesList.getImagegalleryurl().get(i);
keywordresulttab.array_imgurl[i] = name;
}
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
return null;
}
class MyAdapter extends BaseAdapter implements OnClickListener
{
private LayoutInflater inflater;
public MyAdapter(Context ctx) {
super();
this.inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalartist;
}
/* Not implemented but not really needed */
#Override
public Object getItem(int position) {
return null;
}
/* Not implemented but not really needed */
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View ConvertView, ViewGroup parent)
{
View v = inflater.inflate(R.layout.listitem_layout, parent, false);
// Log.i("array galoijewdh..",keywordresulttab.array_galleryname[position]);
Log.i("saurabh trivedi","saurabh trivedui");
// Variables.a=3;
String gallerynames = keywordresulttab.array_galleryname[position];
String addresses = keywordresulttab.array_address[position];
TextView tv = (TextView) v.findViewById(R.id.barrio);
tv.setText(gallerynames);
tv = (TextView) v.findViewById(R.id.ciudad);
tv.setText(addresses);
((BaseAdapter)(getListAdapter())).notifyDataSetChanged();
return v;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
}
}
Make your array list empty on onResume() method and fill it by new content now.
Related
I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}
I've this adapter class :
public class NoteFeedListAdapter extends RecyclerView.Adapter<feedItemsHolder>{
private Activity activity;
private LayoutInflater inflater;
private List<NoteFeedItem> feedItems;
private List<CommentModel> commentItems;
private NoteCommentListAdapter adapter;
private RecyclerView mRecyclerView;
ImageLoader imageLoader = NoteAppController.getInstance().getImageLoader();
private static final String URL_LIST_VIEW_COMMENT = "http://url.com";
private int level = 0;
private Context mContext;
public NoteFeedListAdapter(Context context, List<NoteFeedItem> feedItems) {
this.feedItems = feedItems;
this.mContext = context;
}
public feedItemsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feed_item, null);
feedItemsHolder mh = new feedItemsHolder(v);
return mh;
}
public void onBindViewHolder(final feedItemsHolder fItemsHolder, final int i) {
final NoteFeedItem item = feedItems.get(i);
fItemsHolder.setLevel(item.getLevel());
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
and Inside onBindViewHolder :
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this code is what I used to call asyntask but result from asynctask cannot be shown in this adapter
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
...
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
if(item.getLevel() == Level.LEVEL_ONE){
level = Level.LEVEL_TWO;
}else if(item.getLevel() == Level.LEVEL_TWO){
level = Level.LEVEL_THREE;
}
}
public int getItemCount() {
return (null != feedItems ? feedItems.size() : 0);
}
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personal.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
}else{
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
Toast.makeText(mContext, id_note, Toast.LENGTH_SHORT).show();
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
The problem is that I wanna add data from Asynctask and shown on another adapter. But how can i do that? please help. view from another adapter couldn't show with this code.
In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.
I'm working with json. I parsed the JSON and I can show my JSON (images and text) on ListView. Now I want to show JSON's first item's title in my widget.
I successfully created the widget but I have a problem with the JSON's first item's title.
This is a my code:
public class AppWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "CLOCK_WIDGET_UPDATE";
RemoteViews views;
int appWidgetId;
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
views = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
String aa = (MainActivity.itemList.get(0)
.get(MainActivity.KEY_title)).toString();
views.setOnClickPendingIntent(R.id.widgetPic, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetTitle, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetDesc, pendingIntent);
views.setTextViewText(R.id.widgetDesc, aa);
views.setImageViewBitmap(
R.id.widgetPic,
((BitmapDrawable) context.getResources().getDrawable(
R.drawable.background)).getBitmap());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public void updateAppWidget(Context context,
AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
try {
} catch (Exception e) {
}
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
BaseAdapter.java code:
public class MyAdapter extends BaseAdapter {
Context mContext;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private int screenSize;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> d,
int screenSize) {
this.mContext = context;
this.data = d;
this.screenSize = screenSize;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(context.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.list_row, null);
TextView journal = (TextView) vi.findViewById(R.id.smalljournal);
TextView title = (TextView) vi.findViewById(R.id.smalltitle);
TextView description = (TextView) vi
.findViewById(R.id.smallDescription);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.smallthumb);
TextView statId = (TextView) vi.findViewById(R.id.smallstatID);
TextView DateTime = (TextView) vi.findViewById(R.id.smallDateTime);
HashMap<String, String> itemList = new HashMap<String, String>();
itemList = data.get(position);
journal.setText(itemList.get(MainActivity.KEY_journal));
statId.setText(itemList.get(MainActivity.KEY_statID));
journal.setTypeface(MainActivity.tf2);
String titleString = itemList.get(MainActivity.KEY_title);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// coming date : 2014-02-03T18:45:00
String DateTimeTxt = itemList.get(MainActivity.KEY_pubDate).replace(
"T", " ");
// DateTimeTxt = date;
try {
Date _d = df.parse(DateTimeTxt);
SimpleDateFormat new_df = new SimpleDateFormat("dd.MM.yyyy");
String _s = new_df.format(_d);
DateTime.setText(_s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL)
description.setVisibility(View.INVISIBLE);
else
description.setVisibility(View.VISIBLE);
title.setText(titleString);
title.setTypeface(MainActivity.tf2);
description.setText(itemList.get(MainActivity.KEY_description));
description.setTypeface(MainActivity.tf2);
String url = itemList.get(MainActivity.KEY_image);
// url = url.replace("-c.jpg", ".jpg");
imageLoader.DisplayImage(url, thumb_image);
return vi;
}
}
MainActivity.java code
public class MainActivity extends Activity {
public String URL = "********************";
public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public JSONParser jsonparser;
static MyAdapter adapter;
ProgressDialog pDialog, pDialog1;
static String fontPath2 = "font.ttf";
public static Typeface tf2;
public static ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();
public ImageLoader imageLoader;
static final int DIALOG_ERROR_CONNECTION = 1;
public static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
public ImageView image;
public EditText searchInput;
public LinearLayout mainLayout, SlideLayout;
public TransparentProgressDialog pd;
public Tools tools;
public static boolean CheckListview = true;
private int screenSize;
int windowWidth;
public LoadDataAllChanelsToServer loadData;
public TextView journal, tittle, description, smalllink, DateTime,
smallstatID;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
Writer writer;
public File yourFile;
View menu_Slide;
#SuppressLint("CutPasteId")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
SlideLayout = (LinearLayout) findViewById(R.id.SlideLayout);
list = (ListView) findViewById(R.id.listView1);
cd = new ConnectionDetector(getApplicationContext());
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this,
this));
loadData = new LoadDataAllChanelsToServer();
menu_Slide = (findViewById(R.id.menu_button));
image = (ImageView) findViewById(R.id.imageView1);
searchInput = (EditText) findViewById(R.id.input_search_query);
tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
pd = new TransparentProgressDialog(this, R.drawable.loader);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
journal = (TextView) view.findViewById(R.id.smalljournal);
tittle = (TextView) view.findViewById(R.id.smalltitle);
description = (TextView) view
.findViewById(R.id.smallDescription);
smalllink = (TextView) view.findViewById(R.id.smalllink);
DateTime = (TextView) view.findViewById(R.id.smallDateTime);
smallstatID = (TextView) view.findViewById(R.id.smallstatID);
String Stringjournal = journal.getText().toString();
String Stringtittle = tittle.getText().toString();
String Stringdescription = description.getText().toString();
String Stringlink = smalllink.getText().toString();
String StringdateTime = DateTime.getText().toString();
String StringstatID = smallstatID.getText().toString();
HideKeyBoadr();
Intent in = new Intent(MainActivity.this, Result.class);
in.putExtra("KEY_journal", Stringjournal);
in.putExtra("KEY_title", Stringtittle);
in.putExtra("KEY_description", Stringdescription);
in.putExtra("KEY_link", Stringlink);
in.putExtra("KEY_pubDate", StringdateTime);
in.putExtra("KEY_statID", StringstatID);
String url = itemList.get(position).get(MainActivity.KEY_image);
if (!cd.isConnectingToInternet()) {
in.putExtra("Bitmap", url);
}
else {
if (url.endsWith("-c.jpg"))
url = url.replace("-c.jpg", ".jpg");
in.putExtra("Bitmap", url);
}
in.putExtra("Bitmap", url);
startActivity(in);
overridePendingTransition(R.anim.trans_left_in,
R.anim.trans_left_out);
}
});
if (!cd.isConnectingToInternet()) {
return;
} else {
loadData.execute();
}
}
public void HideKeyBoadr() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
}
private class LoadDataAllChanelsToServer extends
AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected String doInBackground(String... urls) {
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
itemList.add(map);
dateTime = itemList.get(itemList.size() - 1).get(
KEY_pubDate);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return itemList.toString();
}
#Override
protected void onPostExecute(String result) {
try {
if (pd != null) {
pd.dismiss();
}
} catch (Exception e) {
}
try {
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
list.setAdapter(adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
createDialog();
}
private void createDialog() {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Are you sure you want to exit?");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
}
);
alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDlg.create().show();
}
}
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
That is too much code to look at. Please narrow your issue down and show the exact point the issue is occurring at.
Use your debugger to step through your code. 1st, identify the exact line at which the issue is occurring. Next, use your debugger to inspect the variables at that point. The error is an index out of bounds, so you're accessing a point in a list that is bigger than the size of the list.
I am trying to use Endless listview adapter in application code but some how i am just not able to see any values in the listview. My code is running perfectly fine when using normal listview adapter. I an trying to use CWAC- endless adpater. I can get how to run it with my asynctask as it gives me blank screen after loding.
Below is my code for the some.
public class EndlessAdapterExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
static int LIST_SIZE;
private int mLastOffset = 0;
static final int BATCH_SIZE = 10;
ArrayList<EventsBean> countriesSub = new ArrayList<EventsBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "mu Url"
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
init();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
// TODO Auto-generated method stub
// Fetching the position from the listview which has been selected.
}
});
}
private void init() {
new FetchEventValues().execute();
}
private void setLastOffset(int i) {
mLastOffset = i;
}
private int getLastOffset(){
return mLastOffset;
}
private void displayList(ArrayList<EventsBean> countriesSub) {
setListAdapter(new DemoAdapter());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Void, ArrayList<EventsBean>, ArrayList<EventsBean>>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessAdapterExample.this);
ArrayList<EventsBean> merge = new ArrayList<EventsBean>();
ArrayList<EventsBean> localList;
public EventsBean eventsbean;
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected ArrayList<EventsBean> doInBackground(Void... params) {
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
cal = Calendar.getInstance();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if (alldates.compareTo(today) > 0)
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
JSONObject jsonobjname = jsonArray.getJSONObject(i);
eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
localList=null;
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return arrayEventsBeans;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0, arrayEventsBeans);
//listview.setAdapter(adapter);
//displayList(arrayEventsBeans);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
Log.i(TAG, "country list:" + countriesSub.size());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
}
public class SAmpleAdapter extends ArrayAdapter<EventsBean> {
Context context;
public ArrayList<EventsBean> mOriginalvalues;
private ArrayList<EventsBean> mDisplayvalues;
ImageLoader imageloader;
public String datenew,datetime,date_text_value,timenew;
public int date_text,year;
public String time,month,description;
public LayoutInflater inflator = null;
public SAmpleAdapter(Context context, int resource, ArrayList<EventsBean> mEventarraylist) {
super(context, resource , mEventarraylist);
// TODO Auto-generated constructor stub
this.mOriginalvalues = mEventarraylist;
this.mDisplayvalues = mEventarraylist;
inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader=new ImageLoader(context.getApplicationContext());
getFilter();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mOriginalvalues.size();
}
#Override
public EventsBean getItem(int position) {
// TODO Auto-generated method stub
return mOriginalvalues.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder viewHolder;
if(convertView == null)
{
viewHolder=new Holder();
convertView = inflator.inflate(R.layout.activity_list_items, parent, false);
viewHolder.txt_name = (TextView)convertView.findViewById(R.id.textname);
viewHolder.txt_owner_name = (TextView)convertView.findViewById(R.id.ownername);
viewHolder.txt_time = (TextView)convertView.findViewById(R.id.date);
viewHolder.txt_date = (TextView)convertView.findViewById(R.id.txt_date_value);
viewHolder.txt_month = (TextView)convertView.findViewById(R.id.txt_month_value);
viewHolder.txt_year = (TextView)convertView.findViewById(R.id.txt_year_value);
viewHolder.userimg = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
}
else
{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.txt_name.setText(mOriginalvalues.get(position).getName());
viewHolder.txt_owner_name.setText(mOriginalvalues.get(position).getOwner_name());
String url = mOriginalvalues.get(position).getSource();
date_text_value = mOriginalvalues.get(position).getStart_time();
try {
parseDateFromString(date_text_value);
} catch (Exception e) {
Log.i("Adapter TAG", "Date Exception" + e.getMessage());
}
viewHolder.txt_date.setText(String.valueOf(date_text));
viewHolder.txt_month.setText(month);
viewHolder.txt_year.setText(String.valueOf(year));
Log.i("TEST", "Date:" + date_text_value);
imageloader.DisplayImage(url, viewHolder.userimg);
viewHolder.txt_time.setText(timenew);
return convertView;
}
public void resetData() {
mOriginalvalues = mDisplayvalues;
}
#SuppressLint("SimpleDateFormat")
public Date parseDateFromString(String aDateString){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar c = Calendar.getInstance();
Date date= new Date();
try {
date= inputFormat.parse(aDateString);
System.out.println(date);
SimpleDateFormat day = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm a", Locale.getDefault());
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
c.setTime(inputFormat.parse(aDateString));
System.out.println(day.format(date));
datenew = day.format(date).toString();
date_text = c.get(Calendar.DAY_OF_MONTH);
month = month_date.format(c.getTime());
year = c.get(Calendar.YEAR);
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + month);
System.out.println("Day = " + date_text);
System.out.println(time.format(date));
timenew = time.format(date).toString();
} catch (ParseException e) {
Log.i("TAG", "DateFormat Pasring Error:" + e.getMessage());
}
return date;
}
private class Holder{
TextView txt_name;
TextView txt_owner_name ;
TextView txt_time;
TextView txt_date;
TextView txt_month;
TextView txt_year;
ImageView userimg;
}
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<EventsBean> tempList = new ArrayList<EventsBean>();
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DemoAdapter() {
super(new SAmpleAdapter(EndlessAdapterExample.this,R.layout.sample_endless,countriesSub));
inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
View row=getLayoutInflater().inflate(R.layout.row, null);
View child=row.findViewById(R.id.textview1);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
tempList.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempList.add(arrayEventsBeans.get(i));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
return true;
} else {
return false;
}
} else {
return false;
}
}
#SuppressLint("NewApi")
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
ArrayAdapter<EventsBean> arrAdapterNew = (ArrayAdapter<EventsBean>)getWrappedAdapter();
int listLen = tempList.size();
for(int i=0; i<listLen; i++){
arrAdapterNew.addAll(tempList.get(i));
}
}
}
}
I have updated my code. I guess my problem now is with the custom adapter as it gives me multiple values after it reaches the end of the listview. Initially i do get 10 values but after the update it gets same 10 values again but the count reaches to 121.
Replace your init() as below,
private void init() {
new FetchEventValues().execute();
}
and replace onPostExecute() with below,
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if (this.progressdialog.isShowing()) {
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0,
// arrayEventsBeans);
// listview.setAdapter(adapter);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
}