So I am trying to pass some info with serialization, but for some reason it is not working, I wrote a couple of Log.e() for testing, and according to the LogCat it says it is not getting passed the startactivity(intent).
Here is my code
public class MainActivity extends Activity {
FileManager file = new FileManager();
FileInputStream fileInput;
FileOutputStream fileOutput;
SortedArrayList<Contact> contactList = new SortedArrayList<Contact>();
ArrayList<Contact> theList =new ArrayList<Contact>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
fileInput = openFileInput("contacts.txt");
Log.e("FILE INPUT","FOUND!!");
contactList = file.read(fileInput,getApplicationContext());
Log.e("_____",contactList.toString());
}
catch (Exception e) {
Log.e("Error","ERROR CREATING FILE");
}
if(contactList.size() != 0){
ListView lv =(ListView)findViewById(R.id.contactList);
for(int i=0;i<contactList.size();i++){
theList.add(contactList.get(i));
}
ArrayAdapter<Contact> adapter = new MyListAdapter();
lv.setAdapter(adapter);
clickOnContact();
}
// Create The Adapter with passing ArrayList as 3rd parameter
//OrderAdapter arrayAdapter = new OrderAdapter(this, R.layout.list_view, contactListNameView, contactListLastNameView, contactListCellphoneView);
//Set The Adapter
//lv.setAdapter(arrayAdapter);
}
private void clickOnContact() {
ListView list = (ListView) findViewById(R.id.contactList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
long id) {
Contact Contact = theList.get(pos);
Log.e("contact: ",Contact.getFirstName());
try{
Intent intent = new Intent(MainActivity.this, ShowContactActivity.class);
Log.e("pass ","1");
intent.putExtra("Contact",Contact);
Log.e("pass ","2");
startActivity(intent);
}
catch (Exception e){
Log.e("didnt","pass catch");
}
}
});
}
private class MyListAdapter extends ArrayAdapter<Contact> {
public MyListAdapter() {
super(MainActivity.this, R.layout.list_view, theList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.list_view, parent, false);
}
Contact contact = theList.get(position);
//Fill First Name
TextView name = (TextView) itemView.findViewById(R.id.contactName);
name.setText(contact.getFirstName());
//Fill Last Name
TextView lastname = (TextView) itemView.findViewById(R.id.contactLastName);
lastname.setText(contact.getLastName());
return itemView;
}
}
This is the Activity is trying to contact:
public class ShowContactActivity extends Activity {
TextView name;
TextView lastname;
TextView email;
TextView cell;
TextView homenumber;
Contact contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_contact_info);
// Show the Up button in the action bar.
setupActionBar();
name = (TextView) findViewById(R.id.nametextview);
lastname = (TextView) findViewById(R.id.lastnametextview);
email = (TextView) findViewById(R.id.emailtextview);
cell = (TextView) findViewById(R.id.celltextview);
homenumber = (TextView) findViewById(R.id.homenumbertextview);
Contact contact = new Contact();
try{
Intent i = getIntent();
contact = (Contact) i.getSerializableExtra("Contact");
}
catch (Exception e){
Log.e("problema","con serializacion");
}
name.setText(contact.getFirstName());
lastname.setText(contact.getLastName());
cell.setText(contact.getCell());
homenumber.setText(contact.getHomeNumber());
email.setText(contact.getEmail());
}
}
use like
Contact contact = theList.get(pos); //contact is the object of the class (small c)
Related
I want to fetch data from json file from the internet using url, After doing all the codes RecyclerView says no adapter attached. I am not able to find out what is wrong with my code.
public class MainActivity extends AppCompatActivity {
private String urlData = "https://vast-shore-74260.herokuapp.com/banks?city=MUMBAI";
private RecyclerView recyclerView;
private RecyclerView.Adapter Radapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Using this listitem in recyclerView works just fine but when i try to to parse json file, RecyclerView says no adapter attached.
/*listItems = new ArrayList<>();
for (int i=0;i<=10;i++)
{
ListItem listItem = new ListItem(
"SBI"+(i+1),
"Lorem ipsum",
"SBIN00009945",
"khanapara",
"9945",
"ghy",
"kamrup",
"assam"
);
listItems.add(listItem);
}
Radapter = new MyAdapter(listItems,this);
recyclerView.setAdapter(Radapter);*/
Spinner dropdown = findViewById(R.id.spinner);
String[] items = new String[]{"Select City","Mumbai","Bangalore","Chennai"};
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,items)
{
#Override
public boolean isEnabled(int position)
{
if (position == 0)
{
return false;
}
else
{
return true;
}
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View view = super.getDropDownView(position,convertView,parent);
TextView txtView = (TextView)view;
if (position == 0)
{
txtView.setTextColor(Color.GRAY);
}
else
{
txtView.setTextColor(Color.BLACK);
}
return view;
}
};
dropdown.setAdapter(adapter);
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData()
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
urlData,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray(urlData);
for (int i=0; i<array.length();i++)
{
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("bank_name"),
o.getString("address"),
o.getString("ifsc"),
o.getString("branch"),
o.getInt("bank_id"),
o.getString("city"),
o.getString("district"),
o.getString("state")
);
listItems.add(item);
}
/*Radapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(Radapter);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
Log.e("errorcode",error.getMessage());
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
There might be some problem in this code:
Radapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(Radapter);
This is the Adapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItemAdap, Context context) {
this.listItems = listItemAdap;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.txtviewBankName.setText(listItem.getBank_name());
holder.txtviewAddress.setText(listItem.getAddress());
holder.txtviewIfsc.setText(listItem.getIfsc());
holder.txtviewBranch.setText(listItem.getBranch());
holder.txtviewBankId.setText(listItem.getBank_id());
holder.txtviewCity.setText(listItem.getCity());
holder.txtviewDistrict.setText(listItem.getDistrict());
holder.txtviewState.setText(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView txtviewBankName;
public TextView txtviewAddress;
public TextView txtviewIfsc;
public TextView txtviewBranch;
public TextView txtviewBankId;
public TextView txtviewCity;
public TextView txtviewDistrict;
public TextView txtviewState;
public ViewHolder(View itemView) {
super(itemView);
txtviewBankName = (TextView)itemView.findViewById(R.id.bankName);
txtviewAddress = (TextView)itemView.findViewById(R.id.address);
txtviewIfsc = (TextView)itemView.findViewById(R.id.ifsc);
txtviewBranch = (TextView)itemView.findViewById(R.id.branch);
txtviewBankId = (TextView)itemView.findViewById(R.id.bankId);
txtviewCity = (TextView)itemView.findViewById(R.id.city);
txtviewDistrict = (TextView)itemView.findViewById(R.id.district);
txtviewState = (TextView)itemView.findViewById(R.id.state);
}
}
}
Your JSON string has some wrong characters, it should be like this
[{"ifsc":"ABHY0065001","bank_id":60,"branch":"RTGS-HO","address":"ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024","city":"MUMBAI","district":"GREATER MUMBAI","state":"MAHARASHTRA","bank_name":"ABHYUDAYA COOPERATIVE BANK LIMITED"}]
then for parsing this json you can use the com.google.Gson library like this
Type listType = new TypeToken<ArrayList<ListItem>>() {}.getType();
String s = "[{\"ifsc\":\"ABHY0065001\",\"bank_id\":60,\"branch\":\"RTGS-HO\",\"address\":\"ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024\",\"city\":\"MUMBAI\",\"district\":\"GREATER MUMBAI\",\"state\":\"MAHARASHTRA\",\"bank_name\":\"ABHYUDAYA COOPERATIVE BANK LIMITED\"}]";
List<ListItem> items = new Gson().fromJson(s, listType);
then you can set this list as input into your Adapter then assign your adapter to your recycler.
I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
I am developing an android application ,In that i have 3 tabs namely,
1.Invitation tab(it have the invitation listviews)
2.Event tab(it have the event listviewes)
3.Groupchat tab(it have both invitation and event listviewes)
I have a dropdown(that present on dashboard layout) in gropchat tab that have 3 items namely(All,Event,Invitation).Now my need is,I want to filter my Listviews in Groupchat tab based on Dropdown item click functionality(for example,when on tap "Event" item i need to display only the event listviewes).How can i achieve this,Please help me.
My programming code is below,
public class GroupChatFragment extends Fragment {
private Context context;
private ListView chatListView;
private TextView chatTitle;
private TextView chatPlace;
private TextView chatDate;
private String dateResult;
private List<EventMO> groupEventMoList = new ArrayList<>();
private List<EventMO> eventMOs = new ArrayList<>();
private List<EventMO> invitationMOs = new ArrayList<>();
private EventDelegates eventDelegates = new EventDelegates();
private Gson gson = new Gson();
private ProgressDialog prgDialog;
private ChatDisplayAdapter chatDisplayAdapter;
private ListView GroupEventView;
private SharedPreferences sharedpreferences;
private TextView eventList;
private MessageMO messageMO = new MessageMO();
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.all:
return true;
case R.id.event:
return true;
case R.id.invitation:
return true;
}
return super.onOptionsItemSelected(item);
}
public void Event() {
context = getActivity().getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
final UserMO userMO = dbHelper.getRingeeUserData(1);
eventMOs = gson.fromJson(eventDelegates.getAllEventFromUser(userMO, context), new TypeToken<List<EventMO>>() {
}.getType());
List<EventMO> groupEventMOList = new ArrayList<>();
for (EventMO eventMO : eventMOs) {
groupEventMOList.add(eventMO);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.chatwindow_tab, container, false);
context = getActivity().getApplicationContext();
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
DatabaseHelper dbHelper = new DatabaseHelper(context);
final UserMO userMO = dbHelper.getRingeeUserData(1);
prgDialog = new ProgressDialog(getActivity());
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
//inviation group for user
new AsyncTask<Void, Void, List<EventMO>>() {
#Override
protected List<EventMO> doInBackground(Void... arg0) {
eventMOs = gson.fromJson(eventDelegates.getAllEventFromUser(userMO, context), new TypeToken<List<EventMO>>() {
}.getType());
invitationMOs = gson.fromJson(eventDelegates.getAllEventForUser(userMO, context), new TypeToken<List<EventMO>>() {
}.getType());
List<EventMO> groupEventMOList = new ArrayList<>();
for (EventMO eventMO : eventMOs) {
groupEventMOList.add(eventMO);
}
for (EventMO eventMO : invitationMOs) {
groupEventMOList.add(eventMO);
}
return groupEventMOList;
}
#Override
protected void onPostExecute(List<EventMO> groupEventMOList) {
groupEventMoList = groupEventMOList;
prgDialog.dismiss();
DatabaseHelper dbHelper = new DatabaseHelper(context);
//long totalInsertion = dbHelper.insertUserRelationTable(userMOs);
//Toast.makeText(context, "total userMos size " + userMOs.size() + "total db insertion size " + totalInsertion, Toast.LENGTH_LONG).show();
GroupEventView = (ListView) view.findViewById(R.id.chat_list_view);
chatDisplayAdapter = new ChatDisplayAdapter();
GroupEventView.setAdapter(chatDisplayAdapter);
GroupEventView.setItemsCanFocus(true);
GroupEventView.setTextFilterEnabled(true);
GroupEventView.setOnItemClickListener(GroupEventView.getOnItemClickListener());
}
}.execute(null, null, null);
return view;
}
private class ChatDisplayAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ChatDisplayAdapter() {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return groupEventMoList.size();
}
#Override
public Object getItem(int position) {
return groupEventMoList.get(position);
}
#Override
public long getItemId(int id) {
// for sqllite management
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.chatwindow, null);
convertView.setClickable(true);
convertView.setFocusable(true);
chatTitle = (TextView) convertView.findViewById(R.id.chat_title);
chatPlace = (TextView) convertView.findViewById(R.id.event_place);
chatDate = (TextView) convertView.findViewById(R.id.event_date);
chatPlace.setTextColor(getResources().getColor(R.color.black));
chatDate.setTextColor(getResources().getColor(R.color.black));
chatTitle.setTextColor(getResources().getColor(R.color.black));
chatPlace.setText(groupEventMoList.get(position).getPlace());
String actualDate = groupEventMoList.get(position).getEventDate();
//chatDate.setText(groupEventMoList.get(position).getEventDate());
try {
//date format changed here
Date formatDate = new SimpleDateFormat("yyyy-MM-dd").parse(actualDate);
dateResult = new SimpleDateFormat("dd-MM-yyyy").format(formatDate);
} catch (ParseException e) {
e.printStackTrace();
}
chatDate.setText(dateResult);
chatTitle.setText(groupEventMoList.get(position).getText());
convertView.setTag(position);
View v = convertView.findViewById(R.id.chat_window_single);
v.getRootView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("position", v.getTag().toString());
Intent groupAct = new Intent(context, GroupChatActivity.class);
groupAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
groupAct.putExtra("eventMo", groupEventMoList.get(Integer.parseInt(v.getTag().toString())));
startActivity(groupAct);
}
});
}
return convertView;
}
}
}
You should write custom adapter for each Spinner selection, you need to give a category to each one then set data/values of selected categories to the Listview.
This is what i have tried, but my ListView doesn't get filled. I use a custom adapter because i wan't to change the background color of the items that't got a boolean value = true. I am using Android Studio.
Hope someone can help.
i'm new to android.
public class ShoppingListActivity extends ActionBarActivity {
private TextView header;
private ListView listView;
private CustomArrayAdapter arrayAdapter;
private ShoppingList shoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
header = (TextView)findViewById(R.id.textView2);
//get reference to ListView
listView = (ListView)findViewById(R.id.shoppingListItemsView);
shoppingList = (ShoppingList) getIntent().getSerializableExtra(Globals.CHOSENLISTKEY);
arrayAdapter = new CustomArrayAdapter(this, R.layout.custom_list_view, shoppingList.getItemList());
listView.setAdapter(arrayAdapter);
header.setText(shoppingList.toString());
Button btnShop = (Button) findViewById(R.id.btnShop);
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShoppingListActivity.this, SelectStoreActivity.class);
startActivity(intent);
}
});
}
public void setData() {
for(int i = 0; i < shoppingList.getItemList().size(); i++) {
arrayAdapter.add(shoppingList.getItemList().get(i));
}
}
}
public class CustomArrayAdapter extends ArrayAdapter<Entry> {
private int resource;
private ArrayList<Entry> list;
public CustomArrayAdapter(Context context, int resource, ArrayList<Entry> list) {
super(context, resource);
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parentGroup) {
View view = convertView;
Entry entry = list.get((position));
if(view == null) {
LayoutInflater layoutInflater = ((Activity) getContext()).getLayoutInflater();
view = layoutInflater.inflate(resource, parentGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.customName);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
return view;
}
}
To show data in ListView rows call setText method of TextView which is return from getView method:
TextView textView = (TextView) view.findViewById(R.id.customName);
// get Text from entry and pass it to setText method
String strTextViewData=entry.getItem()...;
textView.setText(strTextViewData);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
i have problem with listview... i'm trying to add OnClickListener but in still doesn't work. I want to display another activity after click. Can somebody help me? I know that there are many of example, but it's doesn't work for my appl or i don't know how to use it in my example...
This is my LocationAdapter class:
public class LocationAdapter extends ArrayAdapter<LocationModel> {
int resource;
String response;
Context context;
private LayoutInflater mInflater;
public LocationAdapter(Context context, int resource, List<LocationModel> objects) {
super(context, resource, objects);
this.resource = resource;
mInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView titleGameName;
TextView distanceGame;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
LocationModel lm = (LocationModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.titleGameName = (TextView) convertView
.findViewById(R.id.it_location_title);
holder.distanceGame = (TextView) convertView
.findViewById(R.id.it_location_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleGameName.setText(lm.getGameName());
holder.distanceGame.setText(lm.getGameDistance()+" km");
return convertView;
}
}
This is my mainListView class:
public class SelectGameActivity extends Activity {
LocationManager lm;
GeoPoint userLocation;
ArrayList<LocationModel> locationArray = null;
LocationAdapter locationAdapter;
LocationList list;
ListView lv;
TextView loadingText;
TextView sprawdz;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectgame);
lv = (ListView) findViewById(R.id.list_nearme);
locationArray = new ArrayList<LocationModel>();
locationAdapter = new LocationAdapter(SelectGameActivity.this, R.layout.item, locationArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(locationAdapter);
lv.setItemsCanFocus(true);
String serverName = getResources().getString(R.string.serverAdress);
ApplicationController AC = (ApplicationController)getApplicationContext();
String idPlayer = AC.getIdPlayer();
int latitude = AC.getCurrentPositionLat();
int longitude = AC.getCurrentPositionLon();
int maxDistance = 99999999;
try {
new LocationSync().execute("myserverName");
} catch(Exception e) {}
}
//this is connection with json
private class LocationSync extends AsyncTask<String, Integer, LocationList> {
protected LocationList doInBackground(String... urls) {
LocationList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, LocationList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(LocationList loclist) {
for(LocationModel lm : loclist.getLocations())
{
locationArray.add(lm);
}
locationAdapter.notifyDataSetChanged();
}
}
EDIT:: I have second problem... i want to get id from item (items are downloading from json url) This is my list:
I want to get for example: ID:159 for first item and send it to nextActivity.
I have also the controllerClass.java where i'm setting and getting selectedIdGame:
public String getIdGameSelected() {
return idGame;
}
public void setIdGameSelected(String idGame) {
this.idGame = idGame;
}
Is it good idea? Thanks for help.
Ok, it's done. i used:
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
String idGame = (String) ((TextView) v.findViewById(R.id.idGameSelected)).getText();
Thanks, Michal.
You could define an onItemClick on your adapter instance (i.e. in mainListView.java, just after lv.setAdapter):
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
Intent i = new Intent(v.getContext(), NextActivity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent i = new Intent(view.getContext(), NextActivity.class);
startActivity(i);
}
});
I don't know why this wouldn't work, put it after the try{}catch{} block.