I feel like I'm very close to a solution... I'm getting no errors or crashes, but my text file from my SD card is simply not showing.
Intention: I am trying to read ALL files from a particular directory in my Documents directory on my SD card, then once each file is read, it should be loaded into my ListView via my adapter. I have a model set up (PoemListItem.java), that should retrieve the title of the file, and the contents of the file, both in Strings. I know that it reaches the file in the directory, because when I take away the for loop that adds default text (in case there are not many files in the directory) into the ArrayList<>, then the number of lines in the list are exactly equal to the number of files in the directory. So that part works at least. Only problem is there is nothing showing. Why?
Thanks for your help!
Here you can see that one list item displays (since there is one file in the SD card directory of choice), but that title and text are hint code from the xml, not the actual file title and contents. I assume the hint text is overridden when you import file contents instead? It doesn't seem to be here... The actual title and text that are supposed to be there instead is simply: File name and Test 2... instead of Title and Quote or poem, here.
TextTab.java
package org.azurespot.cutecollection;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import org.azurespot.R;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by mizu on 2/8/15.
*/
public class TextTab extends Fragment {
private ArrayList<PoemListItem> poems = new ArrayList<>();
private ListViewPoemAdapter adapter;
private ListView listView;
String[] allSDCardFiles = null;
StringBuilder text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.text_tab, container, false);
adapter = new ListViewPoemAdapter(getActivity(), poems);
// Attach the adapter to a ListView
listView = (ListView) v.findViewById(R.id.text_list_view);
listView.setAdapter(adapter);
// read contents of SD card
loadSDCard();
// add the default icon/lines remaining to ArrayList, if less than 24 files on SD card
for (int i = 0; i < (24 - allSDCardFiles.length); i++) {
PoemListItem sampleItem = new PoemListItem(" ", " ");
adapter.add(sampleItem);
i++;
}
setupListViewListener();
return v;
}
private void loadSDCard(){
// gets directory CuteWords rom sd card
File baseDir = Environment.getExternalStorageDirectory();
File cuteWordsDir = new File(baseDir, "/Documents/CuteWords");
// lists all files in CuteWords, loads in Files[] array
File[] files = cuteWordsDir.listFiles();
for (File singleFile : files) {
//Read text from file, put each line into StringBuilder
text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(singleFile));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
// add file name and text in file to adapter, to display in ListView
PoemListItem wordsFromFile = new PoemListItem(singleFile.getName(),
text.toString());
adapter.add(wordsFromFile);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// get number of files in CuteWords directory
allSDCardFiles = new String[files.length];
}
// so you can edit any of the list items
private void setupListViewListener() {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter,
View item, int pos, long id){
// code to edit then save typed text
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> aView, View item,
int pos, long id) {
poems.remove(pos);
adapter.notifyDataSetChanged();
// writeItems();
return true;
}
});
}
}
Here is my model:
PoemListItem.java
package org.azurespot.cutecollection;
/**
* Created by mizu on 3/12/15.
*/
public class PoemListItem {
private String title;
private String poem;
public PoemListItem(){}
public PoemListItem(String t, String p){
this.title = t;
this.poem = p;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getPoem(){
return poem;
}
public void setPoem(String poem){
this.poem = poem;
}
}
You probably don't need to see the adapter, but just in case:
ListViewPoemAdapter.java
package org.azurespot.cutecollection;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.azurespot.R;
import java.util.ArrayList;
/**
* Created by mizu on 2/8/15.
*/
public class ListViewPoemAdapter extends ArrayAdapter<PoemListItem> {
private Context context;
private EditText poemText;
private EditText poemTitle;
private ImageView poemPlaceholder;
public ListViewPoemAdapter(Context context, ArrayList<PoemListItem> poems) {
super(context, 0, poems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PoemListItem poemListItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.text_listview_row, parent, false);
}
poemTitle = (EditText) convertView.findViewById(R.id.et_text_title);
poemText = (EditText) convertView.findViewById(R.id.et_text);
poemPlaceholder = (ImageView)convertView.findViewById(R.id.icon_placeholder_poem);
poemPlaceholder.setBackgroundResource(R.drawable.ic_poem_placeholder);
poemPlaceholder.setScaleType(ImageView.ScaleType.CENTER_CROP);
poemPlaceholder.setLayoutParams(new LinearLayout.LayoutParams(150, 150));
// poemTitle.setText(poemListItem.getTitle());
// poemText.setText(poemListItem.getPoem());
return convertView;
}
}
Your arraylist is empty.
Add "wordsFromFile" in arraylist instead of adapter.
Found the mistake! My adapter code that was referencing my model (to hook up my views) was not complete. When you create a model to use for your custom ListView (that has a separate xml file for the list row), then you must include in your model what goes into your list items. In my case, I had two EditText items representing the title and the poem text itself. So my model was missing these lines:
PoemListItem poemListItem = getItem(position);
poemTitle.setText(poemListItem.getTitle());
poemText.setText(poemListItem.getPoem());
Below, you can see them in context. As soon as I uncommented them, I found my List populated with the title and text body in the files from the SD Card. The only reason I had them commented out, was so my hint text from my xml EditTexts would show. Now the hint text does not show on the placeholder lines of the list, but that's a compromise I can live with. So most of my code was right, I just had a few missing lines in my adapter.
ListViewPoemAdapter.java
package org.azurespot.cutecollection;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.azurespot.R;
import java.util.ArrayList;
/**
* Created by mizu on 2/8/15.
*/
public class ListViewPoemAdapter extends ArrayAdapter<PoemListItem> {
private Context context;
private EditText poemText;
private EditText poemTitle;
private ImageView poemPlaceholder;
public ListViewPoemAdapter(Context context, ArrayList<PoemListItem> poems) {
super(context, 0, poems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PoemListItem poemListItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.text_listview_row, parent, false);
}
poemTitle = (EditText) convertView.findViewById(R.id.et_text_title);
poemText = (EditText) convertView.findViewById(R.id.et_text);
poemPlaceholder = (ImageView)convertView.findViewById(R.id.icon_placeholder_poem);
poemPlaceholder.setBackgroundResource(R.drawable.ic_poem_placeholder);
poemPlaceholder.setScaleType(ImageView.ScaleType.CENTER_CROP);
poemPlaceholder.setLayoutParams(new LinearLayout.LayoutParams(150, 150));
poemTitle.setText(poemListItem.getTitle());
poemText.setText(poemListItem.getPoem());
return convertView;
}
Related
I'm having trouble displaying the right String from an ArrayList in my ListView.
My Array (m_aDataList) looks like this:
m_aDataList {ArrayList}
{...}0
m_cText = "R;21;9;River Street 2;12154;;1;.......
m_cTimeStamp = 1556553367492
m_nID = 7
m_nStatus = 0
m_nType = 10002
{...}1
....
This is how I'm currently trying to Display the ArrayList in my ListView:
ArrayAdapter<Message> tuAdapter;
MessageManager tu = new MessageManager();
ArrayList<Message> list = tu.getMessageData();
tuAdapter = new ArrayAdapter<Message>(this, android.R.layout.simple_list_item_1, list);
lvOrders.setAdapter(tuAdapter);
It technically works and adds something like this to my ListView:
de.telematik.testapp.entities.Message#232d9c76
But what I'm trying to do is, only show Messages where m_nType == 10002 and Display them like this in my ListView:
Order: 12154 (order number from m_cText)
Checking weither or not m_nType is = 10002 or 10000 shouldn't be the problem. But how do I get the order number out of the String m_cText and then display it in my ListView?
In any case, thanks for your help.
You are using a basic default list adapter, but you are passing it an array of objects (Message). In order to control what displays in the list, you will need to create your own custom adapter class, that extends (probably base adapter) one of the standard adapter classes. You will call it similarly to the way you pass your list to your simple list adapter. Here is a sample custom list adapter:
ClaimListAdapter.java
package com.mycompany.myapp.adapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.mycompany.myapp.R;
import com.mycompany.myapp.ClaimListFragment;
import com.mycompany.myapp.model.ClaimItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ClaimListAdapter extends BaseAdapter {
private Context context;
private ArrayList<ClaimItem> claimItems;
ClaimListFragment fragment;
public ClaimListAdapter(ClaimListFragment fragment, Context context, ArrayList<ClaimItem> claimItems){
this.context = context;
this.claimItems = claimItems;
this.fragment = fragment;
}
#Override
public int getCount() {
return claimItems.size();
}
#Override
public Object getItem(int position) {
return claimItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// This method gets called for every item in the list when it is about to be displayed in the list
// This helps you get a reference to the layout of the list item
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.claim_list_item, null);
}
// If you have a button that you want to perform some function, such as delete, and then call
// a method back in the parent to update the items in the array, this is one way to do it
Button btnDelete = (Button) convertView.findViewById(R.id.claim_delete_in_list);
// Save the position of the item in the list, so, you know which item was clicked
btnDelete.setTag(position);
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Integer position = (Integer)v.getTag();
// Call this method which is back in the parent, which in this case is a fragment, but could be an Activity
fragment.deleteItemList(position);
}
});
btnDelete.setVisibility(View.GONE);
// Here you get a reference to the various TextViews in your layout
TextView txtTitle = (TextView) convertView.findViewById(R.id.claim_title);
TextView txtStatus = (TextView) convertView.findViewById(R.id.claim_status);
TextView txtDate = (TextView) convertView.findViewById(R.id.claim_date);
TextView txtDistance = (TextView) convertView.findViewById(R.id.claim_distance);
TextView txtAmount = (TextView) convertView.findViewById(R.id.claim_amount);
// Here you get the various strings out of your object for display
String claim_title = claimItems.get(position).getDocumentID();
if (claim_title == null) {
claim_title = "";
}
String claim_status = claimItems.get(position).getClaimStatus();
String claim_date = claimItems.get(position).getClaimDate();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = null;
try {
date = (Date) dateFormat.parse(claim_date);
dateFormat = new SimpleDateFormat("M/d/yyyy");
String formattedDate = dateFormat.format(date);
txtDate.setText(formattedDate);
} catch (ParseException e) {
e.printStackTrace();
}
double total_miles = claimItems.get(position).getTotalMiles();
double total_amount = claimItems.get(position).getTotalAmount();
// Here you set the values in the TextView for display
txtTitle.setText(claim_title);
txtStatus.setText(claim_status);
txtDistance.setText("" + total_miles + "mi");
txtAmount.setText("$" + total_amount);
return convertView;
}
}
Alternatively, you could create a string array containing only the order numbers from your array of messages, and pass that array to your list adapter instead of the array of messages.
I'm testing a simple grid adapter with a custom object, the app runs on the device without a problem but stays blank instead of inflating the activity with the specified grid items. This is my code.
Main Activity
package com.example.nobodyme.errorrepository;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<GridItems> gridItems = new ArrayList<>();
gridItems.add(new GridItems("Android", 2));
gridItems.add(new GridItems("Java", 3));
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new GridViewAdapter(this, gridItems));
}
}
GridViewAdapter
package com.example.nobodyme.errorrepository;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class GridViewAdapter extends ArrayAdapter<GridItems> {
private Context context;
int b;
public GridViewAdapter(Context context, List<GridItems> gridItems) {
super(context, 0, gridItems);
b=gridItems.size();
}
public View getView(int position, View convertView, ViewGroup parent) {
View gridView = convertView;
if(gridView == null)
{
gridView = LayoutInflater.from(getContext()).inflate(
R.layout.grid_view, parent, false);
}
GridItems currentgriditem = getItem(position);
TextView mMaintextView = (TextView) gridView.findViewById(R.id.grid_item_main);
mMaintextView.setText(currentgriditem.getTitle());
TextView mUnansweredtextView = (TextView) gridView.findViewById(R.id.grid_item_unanswered);
mUnansweredtextView.setText(currentgriditem.getUnansweredNo());
return gridView;
}
#Override
public int getCount() {
return b;
}
#Override
public long getItemId(int position) {
return 0;
}
}
GridItems
package com.example.nobodyme.errorrepository;
/**
* Created by nobodyme on 15/1/17.
*/
public class GridItems {
/** Grid title*/
private String mTitle;
/** NO of unanswered items in the gird **/
private Integer mUnansweredNo;
public GridItems(String Title, Integer UnansweredNo) {
mTitle = Title;
mUnansweredNo = UnansweredNo;
}
public String getTitle() {
return mTitle;
}
public Integer getUnansweredNo() {
return mUnansweredNo;
}
}
I have edited the code as per the comments and the app still crashes.
You're overriding getCount and returning zero in the adapter. Don't override this, or return the correct number of items.
Please check below code :
#Override
public int getCount() {
return gridItems.size();
}
Instead of 0 returning, You should return your list size.
You need define gridItems List on your arrayAdapter and set it on the constructor
and override getCount to return the gridItems (adapterGridItems) size
private List<GridItems> adapterGridItems;
public GridViewAdapter(Context context, List<GridItems> gridItems) {
super(context, 0, gridItems);
//set adapterGridItems
this.adapterGridItems=gridItems;
}
#Override
public int getCount() {
return adapterGridItems.size();
}
please, check
mMaintextView.setText(currentgriditem.getUnansweredNo());
you are passing a integer so mMainTextView.setText will find a resource with currentgriditem.getUnansweredNo() id, i think you are trying to set currentgriditem.getUnansweredNo() as string, so this will work
mMaintextView.setText(currentgriditem.getUnansweredNo()+"");
are you sure that is mMaintextView.setText(currentgriditem.getUnansweredNo()+"");
and not
mUnansweredtextView.setText(currentgriditem.getUnansweredNo()+"");
?
In order to tell the adapter how many GridItems to show we need to override the getCount method as shown above by #samsad.
The reason the compiler complains that it can't recognize symbol griditems is because you haven't created a field to store a reference to the GridItems in your adapter.
Try creating a field for the ArrayList of GridItems in your adapter to fix the issue.
I am working on Calendar App to display list of items selected by user. i have set adapter in fragment with 2 array_lists(one for image resources and other for items name) and size of list but rather than to display particular number of list items only first item is coming and get_View method is calling 10 times just for first list element and only one item comes to display.
code of ItemSelectedclass
package shopping.com.shopping.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.ArrayList;
import shopping.com.shopping.R;
public class ItemSelected extends BaseAdapter {
Context mContext;
int limit;
int count=0;
ScrollView sc_list;
private LayoutInflater inflater = null;
String item_name[]={"Egg","Bread","Milk","Watercan","Fruit","Egg","Bread"};
int imgsrc[]={R.drawable.smallegg,R.drawable.smallbread,R.drawable.smallmilk,R.drawable.smallwatert,R.drawable.smallapple,R.drawable.smallegg,R.drawable.smallbread};
ArrayList<String> listofIndexes,listofquantities;
ArrayList<String> location_or_society_details;
public ItemSelected(Context context ,ArrayList<String> listofIndexes,ArrayList<String> listofquantities,int limit) {
// "imgsrc" is the image-reference of selected item from the list
// "quantity" is the quantity of selected item which customer want to book
// "imgTitle" is the name of selected img like milk,bread,watertank
// "getimgSrc[]" is the array which contains refrences of all the items
// "get_title" is the array which contains all the items names
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
this.limit=limit;
this.listofIndexes=listofIndexes;
this.listofquantities=listofquantities;
}
#Override
public int getCount() {
return limit;
}
#Override
public Object getItem(int position) {
return this.listofIndexes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Log.d("testing","afzal");
count++;
TextView i_name=null,i_count=null;
ImageView i_image=null;
if(convertView == null) {
inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.items_list, null);
}
i_image = (ImageView) view.findViewById(R.id.i_image);
i_name = (TextView) view.findViewById(R.id.i_name);
i_count = (TextView) view.findViewById(R.id.i_count);
i_name.setText("testing");
i_count.setText("count");
i_image.setImageResource(R.drawable.logo);
//setting respective value of Booked list_items with 'Item_name' and their 'Quantity'. suppose first user select item#5 with quantity 5 then item#2 with quatity 9 and so on, then first child of listView should b item#5 with quant 5 second list_item should be 2 with quantity 9 and so on
// String index= listofIndexes.get(position);
// String quantity=listofquantities.get(position);
// i_name.setText(item_name[Integer.parseInt(index)]);
// i_image.setImageResource(imgsrc[Integer.parseInt(index)]);
// i_count.setText(Integer.parseInt(quantity));
return view;
}
}
code for TabFragment1 class
package shopping.com.shopping.fragmensts;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.Toast;
import com.samsistemas.calendarview.widget.CalendarView;
import com.samsistemas.calendarview.widget.DayView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import shopping.com.shopping.R;
import shopping.com.shopping.activities.ListItemsActivity;
import shopping.com.shopping.activities.SetOrder;
import shopping.com.shopping.activities.SignUpSignIn;
import shopping.com.shopping.adapter.ItemSelected;
import shopping.com.shopping.adapter.PagerAdapter;
public class TabFragment1 extends Fragment implements View.OnClickListener{
private CalendarView mCalendarView;
private View myFragmentView;
Button btn;
ItemSelected adapter;
ListView listview;
LinearLayout l_lay;
ScrollView scroll;
ArrayList<String> listofIndexes,listofquantities;
int iTem_Index=3;
String item_name[]={"Egg","Bread","Milk","Watercan","Fruit","Egg","Bread"};
int imgsrc[]={R.drawable.smallegg,R.drawable.smallbread,R.drawable.smallmilk,R.drawable.smallwatert,R.drawable.smallapple,R.drawable.smallegg,R.drawable.smallbread};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView= inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
mCalendarView = (CalendarView) myFragmentView.findViewById(R.id.calendar_view);
btn= (Button) myFragmentView.findViewById(R.id.try_it_now);
l_lay = (LinearLayout) myFragmentView.findViewById(R.id.linear);
listview = (ListView) myFragmentView.findViewById(R.id.booked_item);
scroll=(ScrollView)myFragmentView.findViewById(R.id.scroll_list);
SharedPreferences sh_pref=getActivity().getSharedPreferences("backToHome", Context.MODE_PRIVATE);
int flag= sh_pref.getInt("flag", 0);
String item=sh_pref.getString("item","null");
int quantity=sh_pref.getInt("quantity",0);
//if user has booked something then listView in home page will be visible
if(flag==3){
int count=0;
try {
listofIndexes=new ArrayList<String>();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(getActivity().openFileInput("ItemsBooked")));
String readItem;
StringBuffer stringBuffer = new StringBuffer();
while ((readItem = inputReader.readLine()) != null){
listofIndexes.add(readItem);
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
listofquantities=new ArrayList<String>();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(getActivity().openFileInput("Quantity")));
String readQuantity;
StringBuffer stringBuffer = new StringBuffer();
while ((readQuantity = inputReader.readLine()) != null) {
count++;
Toast.makeText(getActivity(), "count is .."+count, Toast.LENGTH_SHORT).show();
listofquantities.add(readQuantity);
}
}
catch (IOException e) {
e.printStackTrace();
}
l_lay.setVisibility(View.GONE);
scroll.setVisibility(View.VISIBLE);
listview.setVisibility(View.VISIBLE);
// after matching and verifying, adding "item" into the array list
adapter= new ItemSelected(getActivity(),listofIndexes,listofquantities,count);
listview.setAdapter(adapter);
}
btn.setOnClickListener(this);
//put intent
mCalendarView.setFirstDayOfWeek(Calendar.SUNDAY);
mCalendarView.setIsOverflowDateVisible(true);
mCalendarView.setCurrentDay(new Date(System.currentTimeMillis()));
mCalendarView.setNextButtonColor(R.color.colorAccent);
mCalendarView.refreshCalendar(Calendar.getInstance(Locale.getDefault()));
mCalendarView.setNextButtonColor(R.color.bg_for_selecte_dday);
mCalendarView.setBackButtonColor(R.color.bg_for_selecte_dday);
//get current date
Date date=new Date(System.currentTimeMillis());
mCalendarView.setCurrentDay(date);
mCalendarView.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
#Override
public void onDateSelected(#NonNull Date selectedDate) {
Toast.makeText(getActivity(), "second date is selected", Toast.LENGTH_SHORT).show();
mCalendarView.setSelectedDayBackground(getResources().getColor(R.color.white));
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
}
});
mCalendarView.setOnMonthChangedListener(new CalendarView.OnMonthChangedListener() {
#Override
public void onMonthChanged(#NonNull Date monthDate) {
SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy", Locale.getDefault());
}
});
final DayView dayView = mCalendarView.findViewByDate(new Date(System.currentTimeMillis()));
return myFragmentView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.try_it_now:
Intent i=new Intent(getActivity(),ListItemsActivity.class);
i.putExtra("flag", 3);
startActivity(i);
}
}
}
I am unable to comment due to low reputation. Kindly post the layout files. Also, instead of using two arraylists and a count variable, create a model class. It will make your code clean and easy to manage.
Refer point no. 12 and 13 from this link http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
New android programmer is here.
First : I dont know many things about list view and as I found out , its complicated to work with it.
So , I want to put my database data (Contains Id , Name) to a listview and get the Id of the item is clicked.
I have searched many but i just found this :
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class test extends Activity {
String[] wordlist = new String[] { "a", "b", "c" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wordlist[2] = "abds";
ListView list = new ListView(this);
list.setAdapter((ListAdapter) new MyAdapter(test.this, wordlist));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Object entry= parent.getItemAtPosition(position);
Toast.makeText(test.this, entry.toString(), Toast.LENGTH_SHORT).show();
}
});
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(test.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
TextView listText = new TextView(test.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
}
Just i can show strings , not Id.
Use SimpleCursorAdapter to populate ListView with data from database, for example - https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/ (first link from google).
How to get the item id in an onItemClick handler
Read more about ListView and Adapters, your code is awful )
I need help on how I list my data in the ListView alphabetical. If I add more data to foldeData it would be nice if I didn't have to manually move the existing data in order to list them alphabetical.
I have copied part of the code from MainActivity:
import java.util.concurrent.TimeUnit;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.ads.*;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener {
TextView minPastaTimer, maxPastaTimer, tv_start, tv_stop, choice;
int minTid, maxTid;
private ListView listViewArticles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Folder[] folderData = new Folder[4];
folderData[0] = new Folder(R.drawable.icon_music_folder, "Acomo Pepe", (getString(R.string.acomo_pepe)), "Kogetid 9-10min");
folderData[1] = new Folder(R.drawable.icon_music_folder, "Bucatini", (getString(R.string.Bucatini)),"Kogetid 9-10min");
folderData[2] = new Folder(R.drawable.icon_music_folder, "Bumbola", (getString(R.string.Bumbola)),"Kogetid 9-10min");
folderData[3] = new Folder(R.drawable.icon_music_folder, "Cannelloni", (getString(R.string.Cannelloni)),"Kogetid 9-10min");
FolderAdapter adapter = new FolderAdapter(this,
R.layout.listview_item_row, folderData);
listViewArticles = (ListView) findViewById(R.id.listView1);
listViewArticles.setAdapter(adapter);
minPastaTimer = (TextView) findViewById(R.id.minPastaTimer);
minPastaTimer.setText("00:00:00");
maxPastaTimer = (TextView) findViewById(R.id.maxPastaTimer);
choice = (TextView) findViewById(R.id.tv_choice);
maxPastaTimer.setText("00:00:00");
Button btn_italy = (Button) findViewById(R.id.btn_italy);
Button btn_danish = (Button) findViewById(R.id.btn_danish);
tv_start = (TextView) findViewById(R.id.tv_start);
tv_start.setOnClickListener(this);
tv_stop = (TextView) findViewById(R.id.tv_stop);
tv_stop.setOnClickListener(this);
listViewArticles.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String listItemText = ((TextView) view
.findViewById(R.id.textViewFolderName))
.getText()
.toString();
Toast.makeText(MainActivity.this,
"You clicked: " + listItemText, Toast.LENGTH_LONG)
.show();
if (listItemText.equals("Acomo Pepe")){
minTid=10000;
maxTid=20000;
choice.setText("Acomo Pepe: " + (getString(R.string.acomo_pepe)));
minPastaTimer.setText("00:08:00");
maxPastaTimer.setText("00:09:00");
}
else if (listItemText.equals("Bucatini")){
minTid=540000;
maxTid=600000;
choice.setText("Bucatini - Kogetid: " + (minTid/60/1000) + ("-") +(maxTid/60/1000) + ("min"));
minPastaTimer.setText("00:09:00");
maxPastaTimer.setText("00:10:00");
}
else if (listItemText.equals("Bumbola")){
minTid=15000;
maxTid=30000;
minPastaTimer.setText("00:10:00");
maxPastaTimer.setText("00:11:00");
}
else if (listItemText.equals("Cannelloni")){
minTid=15000;
maxTid=30000;
minPastaTimer.setText("00:11:00");
maxPastaTimer.setText("00:12:00");
}
}
});
FolderAdapter:
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FolderAdapter extends ArrayAdapter<Folder> {
Context mContext;
int layoutResourceId;
Folder data[] = null;
// #mContext - app context
// #layoutResourceId - the listview_item_row.xml
// #data - the ListItem data
public FolderAdapter(Context mContext, int layoutResourceId, Folder[] data) {
super(mContext, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.data = data;
}
// #We'll overried the getView method which is called for every ListItem we have.
// #There are lots of different caching techniques for Android ListView to
// achieve better performace especially if you are going to have a very long ListView.
// #convertView - the cache of list item row layout, if it is null, inflate new
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
// inflate the listview_item_row.xml parent
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
}
// get the elements in the layout
ImageView imageViewFolderIcon = (ImageView) convertView.findViewById(R.id.imageViewFolderIcon);
TextView textViewFolderName = (TextView) convertView.findViewById(R.id.textViewFolderName);
TextView textViewFolderDescription = (TextView) convertView.findViewById(R.id.textViewFolderDescription);
TextView textViewFolderBoilTime = (TextView) convertView.findViewById(R.id.textViewFolderBoilTime);
// Set the data for the list item. You can also set tags here if you want.
Folder folder = data[position];
imageViewFolderIcon.setImageResource(folder.folderIcon);
textViewFolderName.setText(folder.folderName);
textViewFolderDescription.setText(folder.folderDescription);
textViewFolderBoilTime.setText(folder.folderBoilTime);
return convertView;
}
}
I think best practice would be sorting the list before the calling adaptor.notifyDataChanged() method. Good thing is you do not have to do it manually, just use comparator for sorting.
You can see a comparator example in this link
Instead of using an array as datasource for the list, first use a List. At least, this class extends Collection.
You can define a comparator (e.g define compareTo() on your custom type) and sort your collection before you show it:
Collections.sort(<your_list>);
EDIT: For general collection ordering, see Guava