ArrayList within array adapter remains null - android

I am new to android and my list view is not working correctly. The list displays all the data from an array list as a single row.
My MainActivity looks like this:
public class MainActivity extends FragmentActivity implements OnClickListener{
..
ArrayList<StorylineData> storylineData;
ArrayList<SummaryData> summary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerAPI = (Spinner) findViewById(R.id.spinnerAPI);
mButtonSubmit = (Button) findViewById(R.id.buttonSubmit);
mEditTextResponse = (ListView) findViewById(R.id.editResponse);
mProgressRequest = (ProgressBar) findViewById(R.id.progressRequest);
mButtonSubmit.setOnClickListener(this);
storylineData = new ArrayList<StorylineData>();
...
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
case 0: // Authenticate
...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
...
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", "20140714T073812Z", false);//Date changed to "20150418" "null changed to"20140714T073812Z"
break;
...
toggleProgress(false);
break;
}
}
...
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
updateResponse(
"Date:\t" + result.get(0).getDate() + "\n"
+ "-----------Activity 1 Summary--------\t" + "\n"
+ "Activity:\t" + result.get(0).getActivity().toString() + "\n"//returns 1587 with .getCaloriesIdle()
...
+ "-----------Activity 2 Summary---------\t" + "\n"
+ "Activity:\t" + result.get(0).getSummary().get(0).getActivity() + "\n"//returns 1587 with .getCaloriesIdle()
...
+ "-----------Segments---------\t" + "\n"
+ "Type:\t" + result.get(0).getSegments().get(0).getType() + "\n"//returns 1587 with .getCaloriesIdle()
...
}
public void updateResponse(final String message) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mButtonSubmit.setText(message);
StorylineAdapter adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, storylineData);
mEditTextResponse.setAdapter(adapter);
}
});
}
}
My ArrayAdapter class looks like this:
public class StorylineAdapter extends ArrayAdapter<StorylineData> {
private Context context;
private ArrayList<StorylineData> storylineData;
public StorylineAdapter(Context context, int resource, ArrayList<StorylineData> objects) {
super(context, resource, objects);
this.context = context;
this.storylineData = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_storyline, parent, false);
//Display in the TextView widget
StorylineData storylineData1 = storylineData.get(position);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText(storylineData1.getDistance());
return view;
}
#Override
public int getCount()
{
if (storylineData!=null)
{
return storylineData.size();
}
else
{
Log.e("Adapter", "Summary array is null");
return 0;
}
}
}
Here is my parser class:
public class StorylineData extends ArrayList<StorylineData> {
...Getters/Setters...
/**
* Parse a {#link org.json.JSONObject} from storyline {#link org.json.JSONArray}, then return the corresponding {#link StorylineData} object.
*
* #param jsonObject : the storyline JSON object received from server
* #return corresponding {#link StorylineData}
*/
public static StorylineData parse(JSONObject jsonObject) throws JSONException {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optInt("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
/**Get the data associated with the array named summary **To get a specific JSONArray: Summary*/
JSONArray summariesJsonArray = jsonObject.optJSONArray("summary");
if (summariesJsonArray != null)
for (int i = 0; i < summariesJsonArray.length(); i++) {
/**each time through array will need to get a reference of current object*/
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
/**===============Translate data from json to Java=================*/
/**Create a new OBJECT OF ARRAY STORYLINE/SUMMARY*/
ArrayList<SummaryData> summary = new ArrayList<SummaryData>(); // initialisation must be outside the loop
storylineData.setSummary(summary);
/**Get summary from json into java*/
summariesJsonArray.getJSONObject(i).getString("distance");
/**Get date from json into java*/
String date = summaryJsonObject.optString("date");
storylineData.setDate(date);
/**Get group from json into java*/
String group = summaryJsonObject.optString("group");//Get name using key e.g. date
storylineData.setGroup(group);
...
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("StorylineDataCls \t sJo", summaryJsonObject.toString() + "Log\n");
System.out.println("print distance" + summariesJsonArray.getJSONObject(i).getString("distance"));
System.out.println("print summary" + summaryJsonObject);
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
ArrayList<SegmentData> segments = new ArrayList<SegmentData>(); // initialisation must be outside the loop
storylineData.setSegments(segments);
String type = segment.optString("type");
storylineData.setType(type);
...
storylineData.segments.add(SegmentData.parse(segment));
Log.d("StorylineDataCls \t sSo", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}

Related

Dynamic ListView scroll TextView changed automatically

when i click + button increment the price and click - button decrease the price it's work perfectly but when i scroll listview the value of tvPrices (TextView) is changed.
What should i do for the stay increment price?
here is my adapter
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
price.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
try {
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
ShowHashMapValue();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In onclick, after you decrement the value call notifyDataSetChanged()
notifyDataSetChanged
but its a costly operation, since it refreshes complete list

Sectioning date header in a ListView that has adapter extended by CursorAdapter

I am trying to build a demo chatting App.I want to show the messages with section headers as Dates like "Today","Yesterday","May 21 2015" etc.I have managed to achieve this but since the new View method gets called whenever I scroll the list.The headers and messages get mixed up.
For simplicity, I have kept the header in the layouts itself and changing its visibility(gone and visible) if the date changes.
Can you help me out with this? Let me know if anyone needs any more info to be posted in the question.
public class ChatssAdapter extends CursorAdapter {
private Context mContext;
private LayoutInflater mInflater;
private Cursor mCursor;
private String mMyName, mMyColor, mMyImage, mMyPhone;
// private List<Contact> mContactsList;
private FragmentActivity mActivity;
private boolean mIsGroupChat;
public ChatssAdapter(Context context, Cursor c, boolean groupChat) {
super(context, c, false);
mContext = context;
mMyColor = Constants.getMyColor(context);
mMyName = Constants.getMyName(context);
mMyImage = Constants.getMyImageUrl(context);
mMyPhone = Constants.getMyPhone(context);
mIsGroupChat = groupChat;
mCursor = c;
// mActivity = fragmentActivity;
/*try {
mContactsList = PinchDb.getHelper(mContext).getContactDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
boolean type;
if (mIsGroupChat)
type = cursor.getString(cursor.getColumnIndex(Chat.COLMN_CHAT_USER)).compareTo(mMyPhone) == 0;
else type = cursor.getInt(cursor.getColumnIndex(Chat.COLMN_FROM_ME)) > 0;
if (type) {
return 0;
} else {
return 1;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = null;
int itemViewType = getItemViewType(cursor);
if (v == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (itemViewType == 0) {
v = mInflater.inflate(R.layout.row_chat_outgoing, parent, false);
} else {
v = mInflater.inflate(R.layout.row_chat_incoming, parent, false);
}
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = new ViewHolder();
View v = view;
final Chat chat = new Chat(cursor);
boolean fromMe = mIsGroupChat ? chat.getUser().compareTo(mMyPhone) == 0 : chat.isFrom_me();
if (fromMe) {
// LOGGED IN USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
int color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(color);
holder.chat_name.setText("#You");
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setText(theRest);
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
//holder.chat_text.setText("");
}
updateTimeTextColorAsPerStatus(holder.chat_time, chat.getStatus());
v.setTag(holder);
} else {
// OTHER USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
holder.chat_image = (ImageView) v
.findViewById(R.id.chat_profile_image);
String image = cursor.getString(cursor.getColumnIndex("image"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String color = cursor.getString(cursor.getColumnIndex("color"));
// set the values...
if (holder.chat_image != null) {
MImageLoader.displayImage(context, image, holder.chat_image, R.drawable.round_user_place_holder);
}
int back_color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(back_color);
holder.chat_name.setText(name);
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
Log.d("eywa", "str date is ::::: " + str_date + " pref date is :::::: " + pref_date);
/*if (!TextUtils.isEmpty(pref_date)) {
if (!pref_date.contains(str_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
} else {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
}*/
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
// holder.chat_text.setText("");
}
String phone = cursor.getString(cursor.getColumnIndex("user"));
final Contact contact = new Contact(name, phone, "", color, image);
if (holder.chat_image != null) {
holder.chat_image.setTag(contact);
// holder.chat_name.setTag(contact);
holder.chat_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact con = (Contact) v.getTag();
Intent intent = new Intent(mContext, OtherProfileActivity.class);
intent.putExtra(Constants.EXTRA_CONTACT, con);
mContext.startActivity(intent);
}
});
}
v.setTag(holder);
}
/*else
{
view=
}*/
}
private void updateTimeTextColorAsPerStatus(TextView chat_time, int status) {
if (status == 0) chat_time.setVisibility(View.INVISIBLE);
else {
chat_time.setVisibility(View.VISIBLE);
/* if (status == 1)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.white));*/
if (status == 2)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.darker_gray));
else if (status == 3)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.black));
}
}
#Override
public int getViewTypeCount() {
return 2;
}
public class ViewHolder {
public StyleableTextView chat_name;
public StyleableTextView chat_time;
public StyleableTextView chat_tag;
public ImageView chat_image;
public TextView chat_header_text;
}
#Override
public int getCount() {
if (getCursor() == null) {
return 0;
} else {
return getCursor().getCount();
}
}
}

Custom Adapter to Use Multiple Views in ListView based off of JSON data

I am having trouble creating a Custom Adapter that will allow me to use several different views in a ListView depending on the results from JSON data.
The JSON has 5 different types of data fields and each one needs to have a separate layout. For example, the "text" field needs a TextView and then a EditText element and the "bool" field needs a TextView and a Switch element.
The JSON data could include any variation of the 5 data fields so I can't create a static layout.
I have created a separate xml file for each type of data field.
Below is the current state of my Custom Adapter with some JSON hard coded into it.
Thanks in advance!
public class JobAdapter extends ArrayAdapter<String> {
private static final String JSON_STRING = "{\"title\":\"Unity Gain Amp install\",\"submit\":\"http://dci-services.decisiveinc.net/ampinstall/\n" +
"\n" +
"Submit\",\"sections\":[{\"title\":\"Unity Gain Amp \n" +
"\n" +
"Install\",\"fields\":[{\"name\":\"TechNumber\",\"type\":\"number\",\"label\":\"Tech \n" +
"\n" +
"Number\",\"required\":true,\"stored\":true},{\"name\":\"AmpSerial\",\"type\":\"string\",\"label\":\"Amp Serial \n" +
"\n" +
"#\",\"required\":true,\"stored\":false},{\"name\":\"Account\",\"type\":\"number\",\"label\":\"Account \n" +
"\n" +
"#\",\"required\":true,\"stored\":false}]},{\"title\":\"Reason For Amp \n" +
"\n" +
"Install\",\"fields\":[{\"name\":\"Reason\",\"type\":\"select\",\"label\":\"Reason\",\"required\":true,\"stored\":f\n" +
"\n" +
"alse,\"options\":[{\"key\":\"1\",\"label\":\"Low receive power\"},{\"key\":\"2\",\"label\":\"High \n" +
"\n" +
"Transmit \"},{\"key\":\"3\",\"label\":\"Both\"},{\"key\":\"4\",\"label\":\"Replacement\"}\n" +
"\n" +
"]},{\"name\":\"OldAmpSN\",\"type\":\"string\",\"label\":\"If Replacement: Old Amp \n" +
"\n" +
"SN\",\"required\":false,\"stored\":false}]}]}";
int resource;
String response;
Context context;
//Initialize Adapter
public JobAdapter(Context context, int resource, List<String> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout jobView;
//Get the current job object
String job = getItem(position);
//Inflate the view
if(convertView==null) {
jobView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, jobView, true);
}
else
{
jobView = (LinearLayout) convertView;
}
TextView job_title = (TextView)jobView.findViewById(R.id.job_title);
TextView text_title = (TextView)jobView.findViewById(R.id.job_text_title);
EditText text_input = (EditText)jobView.findViewById(R.id.job_text_input);
TextView select_title = (TextView)jobView.findViewById(R.id.job_select_title);
Spinner select_array = (Spinner) jobView.findViewById(R.id.job_select_spinner);
TextView location_title = (TextView)jobView.findViewById(R.id.job_loc_title);
TextView location_text = (TextView) jobView.findViewById(R.id.job_loc_text);
TextView image_title = (TextView)jobView.findViewById(R.id.job_image_title);
ImageView image_view = (ImageView)jobView.findViewById(R.id.job_image_thumb);
TextView bool_title = (TextView)jobView.findViewById(R.id.job_bool_title);
Switch bool_switch = (Switch)jobView.findViewById(R.id.job_bool_switch);
try {
JSONObject sections =
(new JSONObject(JSON_STRING)).getJSONObject("sections");
String jobtitle = sections.getString("title");
job_title.setText(jobtitle);
JSONObject fields =
(new JSONObject(JSON_STRING)).getJSONObject("sections").getJSONObject("fields");
JSONArray select_options =
(new JSONObject(JSON_STRING)).getJSONObject("sections")
.getJSONObject("fields").getJSONArray("options");
if (fields.getString("type").equals("number")) {
String labelnumber = fields.getString("label");
text_title.setText(labelnumber);
}
if (fields.getString("type").equals("string")) {
String labelstring = fields.getString("label");
text_title.setText(labelstring);
}
if (fields.getString("type").equals("textarea")) {
String labeltextarea = fields.getString("label");
text_title.setText(labeltextarea);
}
if (fields.getString("type").equals("bool")) {
String labelbool = fields.getString("label");
bool_title.setText(labelbool);
}
if (fields.getString("type").equals("select")) {
String labelselect = fields.getString("label");
select_title.setText(labelselect);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Reason");
for (int i = 0; i < select_options.length(); ++i)
{
adapter.add(select_options.getJSONObject(i).getString("label"));
}
select_array.setAdapter(adapter);
select_array.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View itemSelected, int itemkey, long l) {
SharedPreferences.Editor editor = jobData.edit();
editor.putInt(reason_data, itemkey);
editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
if (fields.getString("type").equals("image")) {
String labelimage = fields.getString("label");
image_title.setText(labelimage);
}
if (fields.getString("type").equals("location")) {
String labellocation = fields.getString("label");
location_title.setText(labellocation);
}
} catch (JSONException e) {
e.printStackTrace();
}
return jobView;
}
}

Insert new data in Custom Adapter and update list

I have an list with an custom adapter, and upon refresh I want to add new data to be displayed(if any available).
But the list isn't being update. I tried all the methods with notifyDataSetChanged for the adapter but it's not updated.
Please help. I lost so much time with this and I feel like I'm loosing my mind with this one.
Here is the code:
NewsFeedArrayAdapter
public class NewsFeedArrayAdapter extends ArrayAdapter<FeedItem> {
private final String TAG_DEBUG = this.getClass().getName();
private LayoutInflater inflator;
public final static String PREFS_NAME = "shared_pref_eid";
ImageLoader imageLoader;
Utils utils;
public NewsFeedArrayAdapter(Activity context) {
super(context, R.layout.feed_story_content);
this.utils = new Utils(context);
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = ImageLoader.getInstance(context);
}
/**
* Static Inner class.
*
* Makes the ListView more efficient since Android recycles views in a ListView.
*/
public static class ViewHolder {
public ImageView profilePicture, image;
public TextView author, timePast, message, likes, comments;
public LinearLayout like, comment, share, likesCommentsCounter;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = null;
FeedItem feedItem = FeedItemParser.FEEDS.get(position);
ViewHolder holder = null;
if (convertView == null) {
rowView = inflator.inflate(R.layout.feed_story_content, parent, false);
holder = new ViewHolder();
holder.profilePicture = (ImageView) rowView.findViewById(R.id.feed_story_profile_picture);
holder.author = (TextView) rowView.findViewById(R.id.feed_story_author);
holder.timePast = (TextView) rowView.findViewById(R.id.feed_story_time_past);
holder.message = (TextView) rowView.findViewById(R.id.feed_story_message);
holder.image = (ImageView) rowView.findViewById(R.id.feed_story_image);
holder.like = (LinearLayout) rowView.findViewById(R.id.feed_feedback_like_container);
holder.comment = (LinearLayout) rowView.findViewById(R.id.feed_feedback_comment_container);
holder.share = (LinearLayout) rowView.findViewById(R.id.feed_feedback_share_container);
holder.likes = (TextView) rowView.findViewById(R.id.feed_story_likes);
holder.comments = (TextView) rowView.findViewById(R.id.feed_story_comments);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = ((ViewHolder) rowView.getTag());
}
Log.i(TAG_DEBUG, "feedItem = " + feedItem);
if (feedItem != null) {
if (!TextUtils.isEmpty(feedItem.feed_story_from_name)) {
holder.author.setText(feedItem.feed_story_from_name);
} else {
holder.author.setText("Unknown");
}
if (!TextUtils.isEmpty(feedItem.feed_story_created_time)) {
// Convert the date to calendar date
Calendar calendarDate = null;
try {
calendarDate = ISO8601.toCalendar(feedItem.feed_story_created_time);
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
calendarDate.getTimeInMillis(),
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS);
holder.timePast.setText(relativeTimeSpan);
} else {
holder.timePast.setText("Unknown");
}
Log.i(TAG_DEBUG, "feedItem.feed_story_message = " + feedItem.feed_story_message);
if (!TextUtils.isEmpty(feedItem.feed_story_message)) {
holder.message.setText(feedItem.feed_story_message);
} else {
holder.message.setText("Unkown");
// holder.message.setVisibility(View.GONE);
}
// Display the icon of the feed
int defaultResourceIcon = R.drawable.no_avatar;
if (feedItem.feed_story_from_id != null) {
String iconUrl = "https://graph.facebook.com/" + feedItem.feed_story_from_id + "/picture?type=normal";
if (Session.getActiveSession() != null &&
Session.getActiveSession().getAccessToken() != null) {
iconUrl += "&access_token=" + Session.getActiveSession().getAccessToken();
}
Log.i(TAG_DEBUG, "iconUrl = " + iconUrl);
imageLoader.displayImage(iconUrl, holder.profilePicture, 70, defaultResourceIcon);
} else {
imageLoader.cancelDisplayTaskFor(holder.profilePicture);
holder.profilePicture.setImageResource(defaultResourceIcon);
}
// Display the picture of the feed
int defaultResourcePicture = R.drawable.empty;
if (!TextUtils.isEmpty(feedItem.feed_story_picture)) {
holder.image.setVisibility(View.VISIBLE);
Log.i(TAG_DEBUG, "feed_picture = " + feedItem.feed_story_picture + "\nfeed_picture_height = " + feedItem.feed_story_picture_height);
imageLoader.displayImage(feedItem.feed_story_picture, holder.image, -1, defaultResourcePicture);
} else {
imageLoader.cancelDisplayTaskFor(holder.image);
// holder.image.setImageResource(defaultResourcePicture);
holder.image.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_likes)) {
holder.likes.setVisibility(View.VISIBLE);
String likes = feedItem.feed_story_likes + " like";
if (!feedItem.feed_story_likes.contentEquals("1")) {
likes += "s";
}
holder.likes.setText(likes);
} else {
holder.likes.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(feedItem.feed_story_comments)) {
holder.comments.setVisibility(View.VISIBLE);
String comments = feedItem.feed_story_comments + " comment";
if (!feedItem.feed_story_comments.contentEquals("1")) {
comments += "s";
}
holder.comments.setText(comments);
} else {
holder.comments.setVisibility(View.GONE);
}
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Like content - TBA");
}
});
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Comment section - TBA");
}
});
holder.share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
utils.customToast("Sharing content - TBA");
}
});
}
return rowView;
}
#Override
public int getCount() {
return FeedItemParser.FEEDS.size();
}
}
The adapter on the list is set after the first request, when I get my first results, like this:
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Set the custom adapter
customAddapter = new NewsFeedArrayAdapter(activity);
// Populate the fragment with the data from JSON
actualListView.setAdapter(customAddapter);
FeedItemParser is an custom class where I store my custom objects:
public class FeedItemParser {
// JSON Node names
public static final String
TAG_DATA = "data", // Array
TAG_ID = "id", // String
TAG_FROM = "from", // Object
TAG_FROM_ID = "id", // String
TAG_FROM_CATEGORY = "category", // String
TAG_FROM_NAME = "name", // String
TAG_TO = "to", // Object
TAG_TO_DATA = "data", // Array
TAG_TO_DATA_ID = "id", // String
TAG_TO_DATA_NAME = "name", // String
TAG_MESSAGE = "message", // String
TAG_PICTURE = "picture", // String
TAG_ACTIONS = "actions", // Array
TAG_ACTIONS_NAME = "name", // String
TAG_ACTIONS_LINK = "link", // String
TAG_PRIVACY = "privacy", // Object
TAG_PRIVACY_VALUE = "value", // String
TAG_TYPE = "type", // String
TAG_STATUS_TYPE = "status_type", // String
TAG_CREATED_TIME = "created_time", // String
TAG_UPDATED_TIME = "updated_time", // String
TAG_LIKES = "likes", // Object
TAG_LIKES_COUNT = "count", // String
TAG_COMMENTS = "comments", // Object
TAG_COMMENTS_DATA = "data", // Array
TAG_PAGING = "paging", // Object
TAG_PAGING_PREVIOUS = "previous",// String
TAG_PAGING_NEXT = "next"; // String
/**
* An array of Shelter items.
*/
public static List<FeedItem> FEEDS = new ArrayList<FeedItem>();
/**
* A map of Array items, by ID.
*/
public static Map<String, FeedItem> FEED_MAP = new HashMap<String, FeedItem>();
public static void addItem(FeedItem item) {
FEEDS.add(FEEDS.size(), item);
FEED_MAP.put(item.feed_story_id, item);
}
public static void addPicture (String feed_story_id, String picture, String height) {
FeedItem feedItem = FEED_MAP.get(feed_story_id);
feedItem.feed_story_picture = picture;
feedItem.feed_story_picture_height = height;
}
public static class FeedItem {
public String feed_story_id, feed_story_from_id, feed_story_from_category,
feed_story_from_name, feed_story_message, feed_story_picture, feed_story_picture_height,
feed_story_privacy, feed_story_type, feed_story_status_type, feed_story_created_time,
feed_story_updated_time, feed_story_likes, feed_story_comments;
/**
* #param feed_story_id
* #param feed_story_from_id
* #param feed_story_from_category
* #param feed_story_from_name
* #param feed_story_message
* #param feed_story_picture
* #param feed_story_privacy
* #param feed_story_type
* #param feed_story_status_type
* #param feed_story_created_time
* #param feed_story_updated_time
*/
public FeedItem(String feed_story_id, String feed_story_from_id, String feed_story_from_category,
String feed_story_from_name, String feed_story_message, String feed_story_picture,
String feed_story_picture_height, String feed_story_privacy, String feed_story_type,
String feed_story_status_type, String feed_story_created_time, String feed_story_updated_time,
String feed_story_likes, String feed_story_comments) {
this.feed_story_id = feed_story_id;
this.feed_story_from_id = feed_story_from_id;
this.feed_story_from_category = feed_story_from_category;
this.feed_story_from_name = feed_story_from_name;
this.feed_story_message = feed_story_message;
this.feed_story_picture = feed_story_picture;
this.feed_story_picture_height = feed_story_picture_height;
this.feed_story_privacy = feed_story_privacy;
this.feed_story_type = feed_story_type;
this.feed_story_status_type = feed_story_status_type;
this.feed_story_created_time = feed_story_created_time;
this.feed_story_updated_time = feed_story_updated_time;
this.feed_story_likes = feed_story_likes;
this.feed_story_comments = feed_story_comments;
}
#Override
public String toString() {
return feed_story_message;
}
}
}
When I request new data(refresh), I add the new data in my object (the same way I do the first time):
FeedItemParser.addItem(new FeedItem(
id,
from_id,
from_category,
from_name,
message,
null, // Will be gotten through another request
null,
privacy_value,
type,
status_type,
created_time,
updated_time,
likes,
comments));
After that I call
ListView actualListView = mPullRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
// Sort the list before displaying
Collections.sort(FeedItemParser.FEEDS, Comparators.CREATED_TIME);
// Notify list adapter to update the list
customAddapter.notifyDataSetChanged();
SOLUTION
Based on the recommendations of #Selvin I have managed to update my list after adding more data. Basically I changed my adapter(I'm not using an filtered list anymore, but I'm directly using my custom objects). And after I add new Object, I update the list by calling notifyDataSetChanged() on the existing adapter.
I have also update my code, maybe it will help someone else that is stuck is this situation.
Thanks again #Selvin.

Missing data in Section list view in Android?

I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}

Categories

Resources