Android Data is repeating in my spinner while switching between activities - android

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

Every time you are adding the data to the rowItems object, which you are passing to the spinner adapter
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
So clear the ``rowItems` data before adding the new data
rowItems.clear();
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}

Related

List view not refreshing when item is deleted [duplicate]

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

How to merged same named header in expandable RecyclerView

I have a expandable recycler view as like this
I want to merged same named header(Such as "Nov 17,2016" ). and add their child at one place.
and icon position must be remain same. How to do this?
Here is my json response:
{"Table":
[{"filedate":"Oct 25, 2016","clientid":4},
{"filedate":"Nov 17, 2016","clientid":4},
{"filedate":"Nov 16, 2016","clientid":4}],
"Table1":
[{"filedate":"Oct 25, 2016","file1":"12.txt","category":"Category : Bank Statement"},
{"filedate":"Nov 16, 2016","file1":"Readme.docx","category":"Category : Bank Statement"},
{"filedate":"Nov 17, 2016","file1":"hts-log.txt","category":"Category : Bills"},
{"filedate":"Nov 17, 2016","file1":"cookies.txt","category":"Category : Others",},
{"filedate":"Nov 17, 2016","file1":"readme.txt","category":"Category : Invoice",}]}
Here is my code for getting json response:
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
try {
jsonarray = object.getJSONArray("Table1");
jsonarray1 = object.getJSONArray("Table1");
} catch (JSONException e) {
e.printStackTrace();
}
// JSONArray jsonarray1 = object.getJSONArray("Table2");
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
// Movie movie = new Movie();
// movie.setFiledate(obj.getString("filedate"));
String str = obj.optString("filedate").trim();
Log.d("test", str);
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
// Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
String str2 = obj1.optString("file1").trim();
String str3 = obj1.optString("filename").trim();
String str4 = obj1.optString("category").trim();
Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
if (str == str1) {
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str4));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));
}
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
} Log.d("test", String.valueOf(data));
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapterheader.notifyDataSetChanged();
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Adapeter class
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (type) {
case HEADER:
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
view = inflater.inflate(R.layout.listchild, parent, false);
ListChildViewHolder child = new ListChildViewHolder(view);
return child;
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
boolean showIcon = position > 1 && getItemViewType(position) == CHILD && getItemViewType(position - 2) == HEADER;
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem = item;
itemController1.header_title1.setText(item.text);
itemController1.btn_expand_toggle1.setVisibility((showIcon) ? View.VISIBLE : View.GONE);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
private static class ListChildViewHolder extends RecyclerView.ViewHolder {
public TextView header_title1;
public ImageView btn_expand_toggle1;
public Item refferalItem;
public ListChildViewHolder(View itemView) {
super(itemView);
header_title1 = (TextView) itemView.findViewById(R.id.header_title1);
btn_expand_toggle1 = (ImageView) itemView.findViewById(R.id.btn_expand_toggle1);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
You can use the library SectionedRecyclerViewAdapter to group your Item objects under the same header.
First create a Section class:
class MySection extends StatelessSection {
Item item;
public MySection(Item item) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.item = item;
}
#Override
public int getContentItemsTotal() {
return item.invisibleChildren.size(); // number of items of this section, TODO: check if invisibleChildren is null and return 0
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(item.invisibleChildren.get(position).text);
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(item.text);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Add your Sections to the adapter
sectionAdapter.addSection(new MySection(data.get(0));
sectionAdapter.addSection(new MySection(data.get(1)); //TODO: add a for loop and add all Item objects from data list
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
To make it expandable, follow the example here.

android ListActivity how to populate data with Json Volley Library

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

onitemclick does not work in fragment (custom list view)

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

How to sort & Group in Android?

I have ArrayList and I want to sort and group all data by header in Android.
How it is possible in Android? please help me.below me from owner And set header Me And Joe Manager From owner And set Header in listview. How to do that in Android?
My code in below::
public class Request extends Activity {
private String assosiatetoken;
private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>();
ListView lv;
Button back;
private Spinner spndata;
String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner",
"State" };
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request);
assosiatetoken = MyApplication.getToken();
new doinbackground(this).execute();
back = (Button) findViewById(R.id.button1);
spndata = (Spinner) findViewById(R.id.list_all_quize_req);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reqspinner);
spndata.setAdapter(adapter);
lv = (ListView) findViewById(R.id.listrequestdata);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent edit = new Intent(Request.this, Request_webview.class);
// edit.putExtra("Cat_url", url_link);
startActivity(edit);
}
});
spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate1);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).submitDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 1:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 2:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate3);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).state != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 3:
list = DBAdpter.requestUserData(assosiatetoken);
for (int i = 0; i < list.size(); i++) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
break;
default:
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.submitDate);
d2 = sdf.parse(ord2.submitDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() {
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
String d1 = null;
String d2 = null;
d1 = ord1.state;
d2 = ord2.state;
return d1.compareToIgnoreCase(d2);
}
};
class doinbackground extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
private Context ctx;
public doinbackground(Context c) {
ctx = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ctx);
pd.setMessage("Loading...");
pd.show();
}
#Override
protected Void doInBackground(Void... Params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.cancel();
}
}
public class MyListAdapter extends BaseAdapter {
private ArrayList<All_Request_data_dto> list;
public MyListAdapter(Context mContext,
ArrayList<All_Request_data_dto> list) {
this.list = list;
}
public int getCount() {
return list.size();
}
public All_Request_data_dto getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.custom_request_data, null);
TextView req_id = (TextView) convertView.findViewById(R.id.req_txt);
TextView date = (TextView) convertView.findViewById(R.id.date_txt);
TextView owner = (TextView) convertView
.findViewById(R.id.owner_txt);
TextView state = (TextView) convertView
.findViewById(R.id.state_txt);
req_id.setText(list.get(position).requestId + " - "
+ list.get(position).title);
date.setText(list.get(position).lastModifiedDate + " - "
+ list.get(position).submitDate);
owner.setText(list.get(position).owner);
state.setText(list.get(position).state);
// }
return convertView;
}
}
}
you can make separate list for each category and make a list of these lists and make another list for category names than you can you use ExpandableListView and Adapter for this is like bellow. Here in example, it is used 2d array you can replace this with your list.
public class ExpAdapter extends BaseExpandableListAdapter {
private Context myContext;
String[][] arrChildelements;
String[] arrGroup;
public ExpAdapter(Context context, String[] arrGroup, String[][] arrChild) {
myContext = context;
this.arrGroup = arrGroup;
this.arrChildelements = arrChild;
}
public Object getChild(int groupPosition, int childPosition) {
return null;
}
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
public int getChildrenCount(int groupPosition) {
return arrChildelements[groupPosition].length;
}
public Object getGroup(int groupPosition) {
return null;
}
public int getGroupCount() {
return arrGroup.length;
}
public long getGroupId(int groupPosition) {
return 0;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_row, null);
}
TextView tvGroupName = (TextView) convertView
.findViewById(R.id.tvGroupName);
tvGroupName.setText(arrGroup[groupPosition]);
return convertView;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_row, null);
}
TextView tvPlayerName = (TextView) convertView
.findViewById(R.id.tvPlayerName);
tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);
return convertView;
}
}
you have to write down your own Adapter. You can extends the BaseAdapter, for instance, and override the following methods:
getCount() it iwill returns the number of items in your dataset
getView() it will inflates your view
getItemViewType() Get the type of View that will be created by getView() (the group element Baroque/Classic in your example) or the "normal" item.
getViewTypeCount () the number of type of Views you have.
I am not sure but if you try to short your list then try this for string
public void sort(List<arraylist> itemLocationList) {
if(itemLocationList!=null)
{
Collections.sort(itemLocationList, new Comparator<arraylist>() {
#Override
public int compare(list o1, list o2) {
return o1.res_name.compareToIgnoreCase(o2.res_name);
}
});
}
}
i got solution on my question .Thanks Jignesh!!!
public class Request extends Activity {
private String assosiatetoken;
private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>();
ListView lv;
ExpandableListView exlistView;
ArrayList<String> catOwner = new ArrayList<String>();
ArrayList<String> uniCatOner = new ArrayList<String>();
ArrayList<ArrayList<All_Request_data_dto>> masterOwner = new ArrayList<ArrayList<All_Request_data_dto>>();
ArrayList<String> catState = new ArrayList<String>();
ArrayList<String> uniCatState = new ArrayList<String>();
ArrayList<ArrayList<All_Request_data_dto>> masterState = new ArrayList<ArrayList<All_Request_data_dto>>();
Button back;
private Spinner spndata;
String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner",
"State" };
ArrayAdapter<String> adapter;
ExpAdapter expAdapter;
private void setOwner() {
for (int i = 0; i < list.size(); i++) {
catOwner.add(list.get(i).owner);
}
HashSet<String> hasSetstate = new HashSet<String>(catOwner);
uniCatOner = new ArrayList<String>(hasSetstate);
for (String str : uniCatOner) {
ArrayList<All_Request_data_dto> cats = new ArrayList<All_Request_data_dto>();
masterOwner.add(cats);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < uniCatOner.size(); j++) {
if (uniCatOner.get(j).equals(list.get(i).owner)) {
masterOwner.get(j).add(list.get(i));
}
}
}
}
private void setState() {
for (int i = 0; i < list.size(); i++) {
catState.add(list.get(i).state);
}
HashSet<String> hasSetstate = new HashSet<String>(catState);
uniCatState = new ArrayList<String>(hasSetstate);
for (String str1 : uniCatState) {
ArrayList<All_Request_data_dto> cats = new ArrayList<All_Request_data_dto>();
masterState.add(cats);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < uniCatState.size(); j++) {
if (uniCatState.get(j).equals(list.get(i).state)) {
masterState.get(j).add(list.get(i));
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request);
assosiatetoken = MyApplication.getToken();
list = DBAdpter.requestUserData(assosiatetoken);
exlistView = (ExpandableListView) findViewById(R.id.ExpList);
setOwner();
setState();
new doinbackground(this).execute();
back = (Button) findViewById(R.id.button1);
spndata = (Spinner) findViewById(R.id.list_all_quize_req);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reqspinner);
spndata.setAdapter(adapter);
lv = (ListView) findViewById(R.id.listrequestdata);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent edit = new Intent(Request.this, Request_webview.class);
// edit.putExtra("Cat_url", url_link);
startActivity(edit);
}
});
spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate1);
exlistView.setFocusable(false);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).submitDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 1:
list = DBAdpter.requestUserData(assosiatetoken);
exlistView.setVisibility(View.GONE);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 2:
list = DBAdpter.requestUserData(assosiatetoken);
exlistView.setVisibility(View.GONE);
Collections.sort(list, byDate3);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).state != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 3:
lv.setVisibility(View.GONE);
expAdapter = new ExpAdapter(Request.this, uniCatOner,
masterOwner);
exlistView.setAdapter(expAdapter);
break;
case 4:
lv.setVisibility(View.GONE);
expAdapter = new ExpAdapter(Request.this, uniCatState,
masterState);
exlistView.setAdapter(expAdapter);
break;
default:
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.submitDate);
d2 = sdf.parse(ord2.submitDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() {
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
String d1 = null;
String d2 = null;
d1 = ord1.state;
d2 = ord2.state;
return d1.compareToIgnoreCase(d2);
}
};
class doinbackground extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
private Context ctx;
public doinbackground(Context c) {
ctx = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ctx);
pd.setMessage("Loading...");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.cancel();
}
}
public class MyListAdapter extends BaseAdapter {
private ArrayList<All_Request_data_dto> list;
public MyListAdapter(Context mContext,
ArrayList<All_Request_data_dto> list) {
this.list = list;
}
public int getCount() {
return list.size();
}
public All_Request_data_dto getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.custom_request_data, null);
TextView req_id = (TextView) convertView.findViewById(R.id.req_txt);
TextView date = (TextView) convertView.findViewById(R.id.date_txt);
TextView owner = (TextView) convertView
.findViewById(R.id.owner_txt);
TextView state = (TextView) convertView
.findViewById(R.id.state_txt);
req_id.setText(list.get(position).requestId + " - "
+ list.get(position).title);
date.setText(list.get(position).lastModifiedDate + " - "
+ list.get(position).submitDate);
owner.setText(list.get(position).owner);
state.setText(list.get(position).state);
// }
return convertView;
}
}
}

Categories

Resources