Spannable string returning whole string on click - java

Using Button on a row in the ListView and am able to make a single row Spannable and data from database but when i click it is returning whole string than a word here is my code from MyAdapter Class where am entering values from database to Listview
public View getView(int i, View view, ViewGroup viewGroup) {
Realm realm=Realm.getDefaultInstance();
Word toEdit = realm.where(Word.class)
.equalTo("id", 10).findFirst();
int id_to_seperate=toEdit.getLang();
LayoutInflater inflater= (LayoutInflater) Main.context.getSystemService(Main.context.LAYOUT_INFLATER_SERVICE);
View row= inflater.inflate(R.layout.layout,viewGroup,false);
TextView word= (TextView) row.findViewById(R.id.word_name);
TextView meaning= (TextView) row.findViewById(R.id.word_define);
Word temp=list.get(i);
int idz=temp.getId();
word.setText(temp.getWord());
if(id_to_seperate==idz){
String span[] = temp.getMeaning().substring(1).split(" ") ;
SpannableString ss = new SpannableString(temp.getMeaning().substring(1));
ClickableSpan spans[] = new ClickableSpan[span.length];
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
#Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
int start = 0 ;
int end =0;
try {
for(int spanCount = 0 ; spanCount <span.length ; spanCount++){
if(spanCount==0) {
end += span[spanCount].length();
}else{
end += span[spanCount].length()+1;
}
ss.setSpan(spans[spanCount], start, end , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += span[spanCount].length()+1;
}
} catch (Exception e) {
e.printStackTrace();
}
meaning.setText(ss);
meaning.setMovementMethod(LinkMovementMethod.getInstance());
}else {
meaning.setText(temp.getMeaning().substring(1));
}
return row;
}
am able to get result from a specific row in a list
to this But click Functionality returning whole sentense than a span or word, I would be thankful if anyone can tell me what mistake I have done
Regards

here is wrong in your code
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
TextView.getText().toString() is return full text. if you want to get specific ClickableSpan then use below ClickableSpan
public class SpecialClickableSpan extends ClickableSpan {
String text;
public SpecialClickableSpan(String text){
super();
this.text = text;
}
#Override
public void onClick(View widget) {
Log.d(TAG, "onClick [" + text + "]");
}
}
replace
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
#Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
with
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new SpecialClickableSpan (span[spanCount ]);
}

Related

How to get text from all TextViews RecyclerView

First of all sorry for the language. I have a RecyclerView with items. I have a checkbox in each item. I have onCheckedChangeListener inside RecyclerAdapter.
When I check 4 checkboxes I need to disable the remaining. So how can I get an access for them? I can do it when on create Recycler by checking how many items are selected. But can't find how to get access for every checkbox in onCheckedChange method. Screenshot example
public class EditAtributesAdapter extends RecyclerView.Adapter<EditAtributesAdapter.EditAtributesViewHolder> {
private ArrayList<AtributeEditItem> mEditAtributeList;
DBHelper dbHelper;
public static class EditAtributesViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public CheckBox mCheckBox;
public EditAtributesViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.edit_atribute_icon);
mCheckBox = itemView.findViewById(R.id.enabledAtribute);
}
}
public EditAtributesAdapter(ArrayList<AtributeEditItem> editAtributeList){
mEditAtributeList = editAtributeList;
}
#Override
public EditAtributesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.atribute_edit_item, parent, false);
final Context forClickCTX = parent.getContext();
final EditAtributesViewHolder eavh = new EditAtributesViewHolder(v);
eavh.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = eavh.getAdapterPosition();
// System.out.println("Hello, you clicked: " + mEditAtributeList.get(pos).getName());
dbHelper = new DBHelper(forClickCTX);
try {
dbHelper.createDataBase();}
catch (IOException ioe) {
throw new Error("Не удалось создать базу данных");}
try {
dbHelper.openDataBase();}
catch (SQLException sqle) {
throw sqle;}
int countSelected = 0;
if (countSelected == 0){
Cursor cursor = null;
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
cursor = db.query(DBHelper.TABLE_TASKS, null, "id = " + mEditAtributeList.get(pos).getTask_id(), null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
String ids = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.TASK_ATRIBUTE_ID));
String[] parts = ids.split(",");
int[] ints = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
ints[i] = Integer.parseInt(parts[i]);
}
countSelected = ints.length;
}
} finally {
if (cursor != null)
cursor.close();
}
if(countSelected>=5){
if(!eavh.mCheckBox.isChecked())
eavh.mCheckBox.setEnabled(false);
else
eavh.mCheckBox.setEnabled(true);
}
else
eavh.mCheckBox.setEnabled(true);
}
//here is saving new status to db ( a lot of code)
});
return eavh;
}
#Override
public void onBindViewHolder(EditAtributesViewHolder holder, int position) {
AtributeEditItem currentItem = mEditAtributeList.get(position);
holder.mImageView.setImageResource(currentItem.getImage());
holder.mCheckBox.setText(currentItem.getName());
holder.mCheckBox.setChecked(currentItem.isSelected());
int countSelected = 0;
for (int i = 0 ; i < mEditAtributeList.size() ; i++){
if(mEditAtributeList.get(i).isSelected())
countSelected++;
}
if(countSelected>=5){
if(!holder.mCheckBox.isChecked())
holder.mCheckBox.setEnabled(false);
else
holder.mCheckBox.setEnabled(true);
}
else
holder.mCheckBox.setEnabled(true);
}
#Override
public int getItemCount() {
return mEditAtributeList.size();
}
}
Your adapter and viewholder are actually doing too much, but for a small list you can probably get away with it. Calling the sqldatabse like this onclick can be a bit awkward, i am not sure, but i think you are blocking the main thread with this which means you may notice that onclick slightly freezes your app.
But the simplest way disable the items in your recyclerview is to update the items in your
private ArrayList<AtributeEditItem> mEditAtributeList
and call
notifyDataSetChanged()
on the adapter, as you can then derive the state based on the data

Spannable string not clickable in a custom ListView

Using Button on a row in the ListView and am able to make a single row Spannable and data from database but when i click it is not responding to click here is my code from MyAdapter Class where am entering values from database to Listview
public View getView(int i, View view, ViewGroup viewGroup) {
Realm realm=Realm.getDefaultInstance();
Word toEdit = realm.where(Word.class)
.equalTo("id", 10).findFirst();
int id_to_seperate=toEdit.getLang();
LayoutInflater inflater= (LayoutInflater) Main.context.getSystemService(Main.context.LAYOUT_INFLATER_SERVICE);
View row= inflater.inflate(R.layout.layout,viewGroup,false);
TextView word= (TextView) row.findViewById(R.id.word_name);
TextView meaning= (TextView) row.findViewById(R.id.word_define);
Word temp=list.get(i);
int idz=temp.getId();
word.setText(temp.getWord());
if(id_to_seperate==idz){
String span[] = temp.getMeaning().substring(1).split(" ") ;
SpannableString ss = new SpannableString(temp.getMeaning().substring(1));
ClickableSpan spans[] = new ClickableSpan[span.length];
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
#Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
int start = 0 ;
int end =0;
try {
for(int spanCount = 0 ; spanCount <span.length ; spanCount++){
if(spanCount==0) {
end += span[spanCount].length();
}else{
end += span[spanCount].length()+1;
}
ss.setSpan(spans[spanCount], start, end , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += span[spanCount].length()+1;
}
} catch (Exception e) {
e.printStackTrace();
}
meaning.setText(ss);
}else {
meaning.setText(temp.getMeaning().substring(1));
}
return row;
}
am able to get result from a specific row in a list
to this But click Functionality not working, I would be thankful if anyone can tell me what mistake I have done
Regards
Before return add
meaning.setMovementMethod(LinkMovementMethod.getInstance());
This method enabled clicable on link.

Common TextWatcher Saving Values in JSON Improperly (Replacing old values)

I have created Adapter to store Cart Items with there dynamic quantities.
Adding custom views which Contains Size, No. of Print, Price. In that I have to take No. of Print in EditText from User Input.
onBindViewHolder() of Adapter: In that I have added common TextWatcher for every EditText which is separated by ID passed in Constructor.
/*
* Add Custom View For Size and Price
* */
if (cart.getCartPhotoPrintSize() != null) {
try {
data = cart.getCartPhotoPrintSize().get(position);
if (data != null) {
// Remove the custom view
holder.cartPhotoSizrPriceCustome.removeAllViews();
holder.cartPhotoSizrPriceCustome.setVisibility(View.VISIBLE);
// Local Variable for Storing the size of StudioData Size
int size = cart.getCartPhotoPrintSize().size();
// Loop for set the custom layout
for (int i = 0; i < size; i++) {
// inner Loacl Variable
Studio.StudioSize studioSize = cart.getCartPhotoPrintSize().get(i);
// Layout Inflater For Targeting The RootView Of Context
LayoutInflater inflater = LayoutInflater.from(mContext);
View sizePriceView = inflater.inflate(R.layout.size_price_quantity_layout, null, false);
// Binding the id of TextView
studioSizeTextView = (TextView) sizePriceView.findViewById(R.id.studio_photo_album_size);
studioPriceTextView = (TextView) sizePriceView.findViewById(R.id.studio_photo_album_price);
photoQuantity = (EditText) sizePriceView.findViewById(R.id.photo_quantity);
studioSizeTextView.setId(i);
studioSizeTextView.setText(studioSize.getSize());
studioPriceTextView.setText("" + studioSize.getPrice());
holder.cartPhotoSizrPriceCustome.setTag(cart.getId());
holder.cartPhotoSizrPriceCustome.addView(sizePriceView);
//Add TextWacher For Every EditTextView
photoQuantity.addTextChangedListener(new GeneralTextWatcher(holder, i));
}
}
} catch (Exception e) {
Log.w("TAG", e.getMessage());
}
}
GeneralTextWatcher
private class GeneralTextWatcher implements TextWatcher {
ViewHolder viewHolder;
int id;
public GeneralTextWatcher(ViewHolder viewHolder, int i) {
this.viewHolder = viewHolder;
this.id = i;
Log.e(TAG, "Constructor Calling..");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
totalAmount = 0;
int child = viewHolder.cartPhotoSizrPriceCustome.getChildCount();
int pos = viewHolder.getAdapterPosition();
Log.i("size position : ", "" + id);
Log.i("cart item position : ", "" + pos);
Cart tCart = tempValue.get(pos);
Studio.StudioSize ssTemp = tCart.getCartPhotoPrintSize().get(id);
ssTemp.setQuantity(!TextUtils.isEmpty(s) ? Integer.parseInt(s.toString()) : 0);
for (int j = 0; j < child; j++) {
View view = viewHolder.cartPhotoSizrPriceCustome.getChildAt(j);
EditText editText = (EditText) view.findViewById(R.id.photo_quantity);
TextView textView = (TextView) view.findViewById(R.id.studio_photo_album_price);
Double quantity = 0.0;
if (!editText.getText().toString().equals(""))
quantity = Double.parseDouble(editText.getText().toString());
Double price = Double.parseDouble(textView.getText().toString());
if (printAmount != 0)
tempTotal = printAmount;
printAmount = quantity * price;
totalAmount += printAmount;
}
tempValue.get(pos).setTotal(totalAmount);
((CartActivity) mContext).mValues = tempValue;
Log.e("Tag", "After tmpStr " + new Gson().toJson(
tempValue,
new TypeToken<ArrayList<Cart>>() {
}.getType()));
((CartActivity) mContext).findTotalAmount(tempValue);
}
#Override
public void afterTextChanged(Editable s) {
}
}
When I Change First Cart Item with all three EditText values and Saving new JSON is like Click to see JSON after 3rd EditText filled up Its Working Fine,
But
After changing Second Cart Item fourth EditText Value and Saving JSON like as Click to see after changing 4th EditText in Second Cart Its replacing old Values.
I am getting this problem since last two days. Any help would be appreciated.
Thank you.

Spannable String in Fragment

Im using a SpannableString to color the words which match an existing string.
This works perfectly the first time the fragment is called, the words are found, matched and colored. But the second time the fragment is called, the method which checks for matches and colors the matching words fires, and from the log cat I can see the words are found and matched but not colored.
I'm guessing it has something to do with the lifecycle of the fragment and where SpannableString is being initialized.
I have tried to initialize the SpannableString in onResume(); and in setUserVisibleHint(boolean isVisibleToUser);
This is my approach
public class LessonOne extends ActualFragmetHolder {
#Override
public void init(Bundle savedInstanceState) {
addSlide(FragmentPronounce.newInstance("The cat is jumping over the mouse"));
addSlide(FragmentPronounce.newInstance("This house is really big"));
.....
FragmentPronounce.java
public class FragmentPronounce extends Fragment implements View.OnClickListener,RecognitionListener,TextToSpeech.OnInitListener {
private static final String ARG_OPTION_ONE = "opt1";
private SpannableString hashText;
....
public static FragmentPronounce newInstance(String option1) {
FragmentPronounce sampleSlide = new FragmentPronounce();
Bundle args = new Bundle();
args.putString(ARG_OPTION_ONE, option1);
sampleSlide.setArguments(args);
return sampleSlide;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
if (getArguments() != null && getArguments().size() != 0) {
option1 = getArguments().getString(ARG_OPCTION_ONE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pronounce_material, container, false);
final TextView the_question = (TextView) v.findViewById(R.id.text_user_must_say);
if (theQuestion != 0) {
the_question.setText(theQuestion);
}
//mic button
fabMic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
///starts listening for speech and does its thing
///Im using my own custom speech recognition which works fine
speech.startListening(recognizerIntent);
////check for OnResults()
}
}
#Override
public void onResults(Bundle results) {
//if its a OnResults is fine then
methodToCheckAnswer(results);
....
}
private void methodToCheckAnswer(Bundle results) {
//checks answer and calls method which counts and colors words in string
countAndColorWords();
}
//This is the method which check and colors, it triggers fine every time fragment is called, but it only colors the word the first time is called in the fragment's life cycle
private void countAndColorWords(){
String strRight = rightanswer;
.....
the_question = (TextView) getActivity().findViewById(R.id.text_user_says);
the_question.setText(theQuestion);
System.out.println("The question's TEXT" + String.valueOf(the_question.getText().toString()) + "Tokens counted" + tokensCounted + "Option1" + option1 + "What was spoken " + userAnswered);
hashText = SpannableString.valueOf(the_question.getText().toString());
System.out.println("hashText Value "+hashText+ "Right Answer "+ rightanswer);
Matcher matcher = Pattern.compile("\\S+").matcher(strRight);
Matcher usermatcher = Pattern.compile("\\S+").matcher(userAnswered);
int groupCounted = 0;
groupCounted += matcher.groupCount()+1;
Log.d(TAG, "The position number of groups:"+groupCounted +" "+userAnswered);
int rightAnswerCount = matcher.groupCount();
int userAnswerCount = usermatcher.groupCount();
String rightAnswer;
String userAnswer;
int contadorGroup = 0;;
int matchCounter =0;
contadorGroup += matcher.groupCount() + 1;
while (matcher.find() && usermatcher.find()) {
System.out.println(matcher.start() + ":" + matcher.group());
rightAnswer = matcher.group();
userAnswer = usermatcher.group();
rightAnswerCount += matcher.groupCount();
userAnswerCount += usermatcher.groupCount();
String check = "";
for (int i = 0; i <= rightAnswerCount && i <= userAnswerCount; i++) {
if (matcher.group(i).equalsIgnoreCase(usermatcher.group(i))) {//matcher.group(i) == usermatcher.group(i)
matchCounter++;
check = matcher.group(i);
hashText.setSpan(new ForegroundColorSpan(Color.parseColor("#64DD17")), matcher.start(), matcher.end(), i);
}
}
}
//hashText.setSpan(new ForegroundColorSpan(Color.parseColor("#64DD17")), matcher.start(), matcher.end(), palabraColor);
the_question.setText(hashText);
}
Sorry for spaghetti code, tried cleaning it up best I could after trying 100 different things.

unable to bold or highlight event dates of android Custom calendar

#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
Locale.setDefault(Locale.US);
test1 = "2014-11-08";
test2 = "2014-11-07";
test3 = "2014-12-08";
test4 = "2014-12-04";
rLayout = (LinearLayout) findViewById(R.id.text);
tvView = (TextView)findViewById(R.id.tvView);
tvView1 = (TextView)findViewById(R.id.tvView1);
tvView2 = (TextView)findViewById(R.id.tvView2);
tvView3 = (TextView)findViewById(R.id.tvView3);
tvView4 = (TextView)findViewById(R.id.tvView4);
tvView5 = (TextView)findViewById(R.id.tvView5);
tvView3.setVisibility(View.GONE);
tvView4.setVisibility(View.GONE);
tvView5.setVisibility(View.GONE);
month = (GregorianCalendar) Calendar.getInstance();
itemmonth = (GregorianCalendar) month.clone();
items = new ArrayList<String>();
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
handler = new Handler();
handler.post(calendarUpdater);
TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);
previous.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setPreviousMonth();
refreshCalendar();
tvView.setVisibility(View.GONE);
}
});
RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setNextMonth();
refreshCalendar();
tvView.setVisibility(View.GONE);
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
TextView cdate = (TextView)v.findViewById(R.id.date);
if(cdate instanceof TextView && !cdate.getText().equals(""))
{
TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
testMonth=title.getText().toString();
String day = cdate.getText().toString();
Toast.makeText(getApplicationContext(),day+" "+testMonth,Toast.LENGTH_SHORT).show();
}
// removing the previous view if added
if (rLayout.getChildCount() > 0) {
// rLayout.removeAllViews();
}
desc = new ArrayList<String>();
date = new ArrayList<String>();
((CalendarAdapter) parent.getAdapter()).setSelected(v);
String selectedGridDate = CalendarAdapter.dayString
.get(position);
tvView.setVisibility(View.VISIBLE);
tvView3.setVisibility(View.VISIBLE);
tvView4.setVisibility(View.VISIBLE);
tvView5.setVisibility(View.VISIBLE);
if(test1.equals(selectedGridDate))
{
tvView.setText("My Goal");
tvView.setTextColor(Color.RED);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
}
else if(test2.equals(selectedGridDate))
{
tvView.setText("Passion of a Student");
tvView.setTextColor(Color.RED);
tvView1.setText("Creating my own Goal");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("Circular Task");
tvView2.setTextColor(Color.GREEN);
}
else if(test3.equals(selectedGridDate))
{
tvView.setText("My test Passion");
tvView.setTextColor(Color.RED);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
}
else if(test3.equals(selectedGridDate))
{
tvView.setText("My test Task");
tvView.setTextColor(Color.RED);
}
else
{
tvView.setText("No task found");
tvView.setTextColor(Color.MAGENTA);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
tvView2.setTextColor(Color.GREEN);
tvView3.setVisibility(View.GONE);
tvView4.setVisibility(View.GONE);
tvView5.setVisibility(View.GONE);
}
String[] separatedTime = selectedGridDate.split("-");
String gridvalueString = separatedTime[2].replaceFirst("^0*",
"");// taking last part of date. ie; 2 from 2012-12-02.
int gridvalue = Integer.parseInt(gridvalueString);
// navigate to next or previous month on clicking offdays.
if ((gridvalue > 10) && (position < 8)) {
setPreviousMonth();
refreshCalendar();
} else if ((gridvalue < 7) && (position > 28)) {
setNextMonth();
refreshCalendar();
}
((CalendarAdapter) parent.getAdapter()).setSelected(v);
for (int i = 0; i < Utility.startDates.size(); i++) {
if (Utility.startDates.get(i).equals(selectedGridDate)) {
desc.add(Utility.nameOfEvent.get(i));
}
}
if (desc.size() > 0) {
for (int i = 0; i < desc.size(); i++) {
TextView rowTextView = new TextView(CalendarView.this);
// set some properties of rowTextView or something
rowTextView.setText("Event:" + desc.get(i));
rowTextView.setTextColor(Color.BLACK);
// add the textview to the linearlayout
rLayout.addView(rowTextView);
}
}
desc = null;
}
});
}
protected void setNextMonth() {
if (month.get(Calendar.MONTH) == month
.getActualMaximum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR) + 1),
month.getActualMinimum(Calendar.MONTH), 1);
} else {
month.set(Calendar.MONTH,
month.get(Calendar.MONTH) + 1);
}
}
protected void setPreviousMonth() {
if (month.get(Calendar.MONTH) == month
.getActualMinimum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR) - 1),
month.getActualMaximum(Calendar.MONTH), 1);
} else {
month.set(Calendar.MONTH,
month.get(Calendar.MONTH) - 1);
}
}
protected void showToast(String string) {
Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
}
public void refreshCalendar() {
TextView title = (TextView) findViewById(R.id.title);
adapter.refreshDays();
adapter.notifyDataSetChanged();
handler.post(calendarUpdater); // generate some calendar items
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
}
public Runnable calendarUpdater = new Runnable() {
#Override
public void run() {
items.clear();
// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String itemvalue;
event = Utility.readCalendarEvent(CalendarView.this);
Log.d("=====Event====", event.toString());
Log.d("=====Date ARRAY====", Utility.startDates.toString());
for (int i = 0; i < Utility.startDates.size(); i++) {
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(Calendar.DATE, 1);
items.add(Utility.startDates.get(i).toString());
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
here I able to see all events while clicking on a particular date,but my requirement is also show the dates with bold style or any other color view that containing events without clicking gridview items.My adapter class as follows:::
public class CalendarAdapter extends BaseAdapter {
private Context mContext;
private java.util.Calendar month;
public GregorianCalendar pmonth;
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int lastWeekDay;
int leftDays;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
private ArrayList<String> items;
public static List<String> dayString;
private View previousView;
public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public void setItems(ArrayList<String> items) {
for (int i = 0; i != items.size(); i++) {
if (items.get(i).length() == 1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
#Override
public int getCount() {
return dayString.size();
}
#Override
public Object getItem(int position) {
return dayString.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_layout, null);
}
dayView = (TextView) v.findViewById(R.id.date);
// separates daystring into parts.
String[] separatedTime = dayString.get(position).split("-");
// taking last part of date. ie; 2 from 2012-12-02
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
// checking whether the day is in current month or not.
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
// setting offdays to white color.
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.BLUE);
}
if (dayString.get(position).equals(curentDateString)) {
setSelected(v);
previousView = v;
} else {
v.setBackgroundResource(R.drawable.list_item_background);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = dayString.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(Calendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
// show icon if date is not empty and it exists in the items array
ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
if (date.length() > 0 && items != null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
} else {
iw.setVisibility(View.INVISIBLE);
}
return v;
}
public View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(Calendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(Calendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(Calendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(Calendar.DATE, 1);
dayString.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(Calendar.MONTH) == month
.getActualMinimum(Calendar.MONTH)) {
pmonth.set((month.get(Calendar.YEAR) - 1),
month.getActualMaximum(Calendar.MONTH), 1);
} else {
pmonth.set(Calendar.MONTH,
month.get(Calendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(Calendar.DAY_OF_MONTH);
return maxP;
}
}
Atlast I had already solved my problem changing my Runnable calendar updater as follows:
public Runnable calendarUpdater = new Runnable() {
#Override
public void run()
{
items.clear();
// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String itemvalue;
for (int i = 0; i < 7; i++)
{
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(Calendar.DATE, 1);
items.add("2014-12-08");
items.add("2014-12-04");
items.add("2014-11-07");
items.add("2014-11-08");
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
Now I can see the events without clicking gridView items what I want.Thanx all of you guys for your kind cooperation in this regard. but now issue is how can I also show this event on android google calendar.

Categories

Resources