Android: clear the listview data on button click - android

In my app I have a listview where it is loading data based on the search keyword, now I want to clear the loaded data on button click.
#Override
protected void onPreExecute() {
SearchUtils searchUtils = null;
List<Place> searchResult = null;
String searchType = null;
Log.d(TAG, "onPreExecute start=");
// show your dialog
super.onPreExecute();
Log.d(TAG, "LoadMenuSearch isOldDataToLoad : " + isOldDataToLoad);
if(!this.isOldDataToLoad){
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Button morerecords = (Button) activity.findViewById(R.id.morerecords);
morerecords.setVisibility(View.GONE);
morerecords.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Do Nothing........................");
}
});
//morerecords.setVisibility(View.VISIBLE);
final Button closesearch = (Button) activity.findViewById(R.id.closesearch);
closesearch.setVisibility(View.VISIBLE);
closesearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ListView menuSearchListView = (ListView) activity
.findViewById(R.id.menusearchlist);
searchAdapter.clear();
searchAdapter.notifyDataSetChanged();
closesearch.setVisibility(View.GONE);
}
});
Here in the preexecute I have a button, now when I click the button loaded data should be clear and the listview should get refreshed.
my search adaptor
public SearchAdapter(Activity activity, int viewResourceId, int renderer,
double latitute, double longitute, String menuId,
ArrayList<Neighborhood> nhdDetails,
ArrayList<AttractionData> items, boolean isAddressBook,
boolean isRecommended) {
super(activity, viewResourceId, items);
streetView = new StreetViewUtils(activity);
streetView.loadHtml();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) (getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
view = inflater.inflate(renderer, null);
}
attractionData = items.get(position);
Log.d(TAG, "attractionData " + attractionData + " for position "
+ position);
TextView textName = (TextView) view.findViewById(R.id.textName);
TextView textAddress = (TextView) view.findViewById(R.id.textAddress);
TextView textPhone = (TextView) view.findViewById(R.id.textPhone);
addFavorite = (ImageView) view.findViewById(R.id.pinsave);
LinearLayout itemlayer = (LinearLayout) view
.findViewById(R.id.itemlayer);
itemlayer.setTag(attractionData);
textName.setText(attractionData.getfName());
if (!isRecommended) {
TextView mapidDisplay = (TextView) view.findViewById(R.id.mapid);
mapidDisplay.setTextSize(Constants.defaultFontSize + 2);
if (isAddressBook) {
mapidDisplay.setBackgroundColor(Color.YELLOW);
mapidDisplay.setTextColor(Color.BLACK);
} else {
mapidDisplay.setBackgroundColor(Color.RED);
mapidDisplay.setTextColor(Color.WHITE);
}
mapidDisplay.setTag(attractionData);
mapidDisplay.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
focusLication(v, event);
return true;
}
});
Log.d(TAG,
"attractionData.getLatitude() ----->"
+ attractionData.getLatitude()
+ " attractionData.getLongitude()---> "
+ attractionData.getLongitude());
if (attractionData.getLatitude() != 0
&& attractionData.getLongitude() != 0) {
mapidDisplay.setText(" " + abbrMapId + (position + 1) + " ");
mapidDisplay.setVisibility(View.VISIBLE);
} else {
mapidDisplay.setVisibility(View.GONE);
}
} else {
ImageView acceptRecommend = (ImageView) view
.findViewById(R.id.acceptRecommend);
ImageView rejectRecommend = (ImageView) view
.findViewById(R.id.rejectRecommend);
acceptRecommend.setVisibility(View.VISIBLE);
rejectRecommend.setVisibility(View.VISIBLE);
acceptRecommend.setTag(attractionData);
rejectRecommend.setTag(attractionData);
acceptRecommend.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v).getTag();
((CityPreferences) activity.getApplication()).updateRecommended(data);
items.remove(position);
notifyDataSetChanged();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
rejectRecommend.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v).getTag();
long id = data.getId();
((CityPreferences) activity.getApplication()).deleteSavedAttractions(data);
data.setStatus("unselect");
items.remove(position);
notifyDataSetChanged();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
}
textAddress.setText(attractionData.getAddress());
TextView distance = (TextView) view.findViewById(R.id.distance);
ImageView distanceDir = (ImageView) view
.findViewById(R.id.distancedirection);
Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.navigationdir);
float newRot = new Float(attractionData.getNavigationAngle());
Matrix matrix = new Matrix();
matrix.postRotate(newRot);
// Log.d(TAG, "Roating the Navigation Image : 01" +
// Constants.mOrientation[0]);
if (Constants.mOrientation != null && Constants.mOrientation.length > 0) {
double bearingToTarget = newRot + Constants.mOrientation[0];
double drawingAngle = Math.toRadians(bearingToTarget)
- (Math.PI / 2);
float cos = (float) Math.cos(drawingAngle);
float sin = (float) Math.sin(drawingAngle);
matrix.setSinCos(sin, cos);
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
distanceDir.setImageBitmap(redrawnBitmap);
// distanceDir.setRotation(90);
} else {
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
distanceDir.setImageBitmap(redrawnBitmap);
}
if (attractionData.getDistance() != null
&& !attractionData.getDistance().equals("")) {
distance.setText(attractionData.getDistance());
} else {
distance.setText("");
}
if (attractionData.getLatitude() != 0.00
&& attractionData.getLongitude() != 0.00) {
distanceDir.setVisibility(View.VISIBLE);
distance.setVisibility(View.VISIBLE);
} else {
distanceDir.setVisibility(View.GONE);
distance.setVisibility(View.GONE);
}
// Log.d(TAG, "end to search distance -->");
LinearLayout llReviews = (LinearLayout) view
.findViewById(R.id.reviewsrating);
llReviews.setVisibility(View.VISIBLE);
GridView gridview = (GridView) view.findViewById(R.id.ratingView);
TextView textRating = (TextView) view.findViewById(R.id.rating);
TextView textReviews = (TextView) view.findViewById(R.id.reviews);
textRating.setText("(" + attractionData.getRating() + ")");
gridview.setAdapter(new ImageAdapter(getContext(), attractionData
.getRating()));
// code for review
if (attractionData.getReview() != null
&& (attractionData.getReview().equals("1") || attractionData
.getReview().equals("0"))) {
textReviews.setText(attractionData.getReview() + " review");
} else if (attractionData.getReview() != null) {
textReviews.setText(attractionData.getReview() + " reviews");
} else {
textReviews.setText("0 review");
}
textReviews.setTag(attractionData.getReviewUrl());
textReviews.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String webURL = (String) v.getTag();
utils.openWebURL(v.getContext(), webURL);
}
});
if (Constants.isDefineNeighbourHood) {
addFavorite.setVisibility(View.GONE);
} else {
if (attractionData.getId() > 0) {
if (menuId != null && menuId.equalsIgnoreCase(Constants.menuFavouritePlaceId)) {
addFavorite.setImageResource(R.drawable.favorite_active);
addFavorite.setVisibility(View.GONE);
attractionData.setStatus("select");
EditAttraction editAttraction = new EditAttraction(activity, false);
itemlayer.setOnLongClickListener(editAttraction);
if (!Constants.isEysonly) {
Loginmyplaces loginmyplaces = new Loginmyplaces(activity);
itemlayer.setOnClickListener(loginmyplaces);
}
} else {
addFavorite.setImageResource(R.drawable.favorite_active);
addFavorite.setVisibility(View.VISIBLE);
attractionData.setStatus("select");
EditAttraction editAttraction = new EditAttraction(activity, true);
itemlayer.setOnLongClickListener(editAttraction);
}
} else {
addFavorite.setVisibility(View.VISIBLE);
addFavorite.setImageResource(R.drawable.favorite);
attractionData.setStatus("unselect");
EditAttraction editAttraction = new EditAttraction(activity,
true);
itemlayer.setOnLongClickListener(editAttraction);
}
}
// Log.d(TAG, "Constants.totalFavorite : status : " +
// attractionData.getStatus() + " for " + attractionData.getName());
addFavorite.setTag(attractionData);
addFavorite.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) ((ImageView) v)
.getTag();
ImageView currentpinsave = (ImageView) v
.findViewById(R.id.pinsave);
Log.d(TAG,
"Constants.totalFavorite : status : "
+ data.getStatus());
Log.d(TAG, "Constants.totalFavorite : Resource : "
+ currentpinsave);
if (data.getStatus() != null
&& data.getStatus().equalsIgnoreCase("select")) {
Log.d(TAG, "data.status " + data.getStatus());
currentpinsave.setImageResource(R.drawable.favorite);
currentpinsave.setTag(data);
long id = data.getId();
((CityPreferences) activity.getApplication())
.deleteSavedAttractions(data);
data.setStatus("unselect");
currentpinsave.setImageResource(R.drawable.favorite);
new DeleteFromConstance().execute(id);
} else {
Log.d(TAG, "data.status " + data.getStatus());
currentpinsave
.setImageResource(R.drawable.favorite_active);
currentpinsave.setTag(data);
data.setMenuId(menuId);
streetView.checkPhotoView(data);
((CityPreferences) activity.getApplication())
.saveMyAttractions(data, true);
data.setStatus("select");
utils.checkFavoriteCity(activity, data);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
if (!isRecommended) {
if (attractionData.getImages() != null) {
Log.d(TAG, "ImageUtils --> inside blob saved");
ImageView placeImage = (ImageView) view
.findViewById(R.id.placeimage);
placeImage.setVisibility(View.VISIBLE);
placeImage.setImageBitmap(attractionData.getImages());
} else {
Log.d(TAG, "ImageUtils --> inside blob not saved");
ImageView placeImage = (ImageView) view
.findViewById(R.id.placeimage);
placeImage.setVisibility(View.GONE);
}
}
ImageView navigationImage = (ImageView) view
.findViewById(R.id.navigationImage);
ImageView streetViewImage = (ImageView) view
.findViewById(R.id.streetview);
if (attractionData.getLatitude() != 0
&& attractionData.getLongitude() != 0) {
navigationImage.setImageResource(R.drawable.navigation);
navigationImage.setTag(attractionData);
navigationImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (utils.isConnectionAvailable(v.getContext())) {
Intent intent = new Intent(v.getContext(), Navigator.class);
AttractionData data = (AttractionData) ((ImageView) v).getTag();
Bundle bundle = new Bundle();
// add data to bundle
bundle.putString("startlatitude", latitute + "");
bundle.putString("startlongitude", longitute + "");
bundle.putString("latitude", data.getLatitude() + "");
bundle.putString("longitude", data.getLongitude() + "");
intent.putExtras(bundle);
v.getContext().startActivity(new Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
} else {
Toast.makeText(v.getContext(), v.getContext().getResources().getString(R.string.noconnection), Toast.LENGTH_LONG).show();
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
streetViewImage.setTag(attractionData);
streetViewImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData data = (AttractionData) v.getTag();
Location location = new Location("");
location.setLatitude(data.getLatitude());
location.setLongitude(data.getLongitude());
streetView.checkStreetView(location);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}});
streetViewImage.setVisibility(View.VISIBLE);
navigationImage.setVisibility(View.VISIBLE);
} else {
streetViewImage.setVisibility(View.GONE);
navigationImage.setVisibility(View.GONE);
}
LinearLayout commentLayout = (LinearLayout) view
.findViewById(R.id.commentLayout);
if (attractionData.getComments() != null
&& !attractionData.getComments().trim().equals("")) {
commentLayout.setVisibility(View.VISIBLE);
TextView comment = (TextView) view.findViewById(R.id.comment);
comment.setText(attractionData.getComments());
} else {
commentLayout.setVisibility(View.GONE);
}
ImageView phImage = (ImageView) view.findViewById(R.id.phoneImage);
String phoneNo = attractionData.getPhoneNo();
if (attractionData.getMobileNo() != null
&& !attractionData.getMobileNo().equals("")
&& !attractionData.getMobileNo().equalsIgnoreCase("null")) {
if (phoneNo != null && !phoneNo.equals("")
&& !phoneNo.equalsIgnoreCase("null")) {
phoneNo = phoneNo + ",\n" + attractionData.getMobileNo();
} else {
phoneNo = attractionData.getMobileNo();
}
}
Log.d(TAG, "------------------> phoneNo " + phoneNo);
if (phoneNo != null && !phoneNo.equals("") && !phoneNo.equalsIgnoreCase("null")) {
textPhone.setText(phoneNo);
textPhone.setVisibility(View.VISIBLE);
phImage.setVisibility(View.VISIBLE);
phImage.setImageResource(R.drawable.phone);
phImage.setTag(phoneNo);
phImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
String phone = (String) ((ImageView) v).getTag();
Log.d(TAG, "onTouch phone--" + phone);
utils.dailPhone(v.getContext(), phone);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
} else {
phImage.setVisibility(View.GONE);
textPhone.setVisibility(View.GONE);
}
LinearLayout htmllayout = (LinearLayout) view
.findViewById(R.id.htmllayout);
if (attractionData.getHtmlAttributions() != null
&& !attractionData.getHtmlAttributions().equals("")
&& !attractionData.getHtmlAttributions().equalsIgnoreCase(
"null")) {
htmllayout.setVisibility(View.VISIBLE);
TextView htmlAttributions = (TextView) view
.findViewById(R.id.htmlAttributions);
TextView htmlAttributionsLink = (TextView) view
.findViewById(R.id.htmlAttributionsLink);
htmlAttributions.setText(attractionData.getHtmlAttributions());
htmlAttributionsLink.setText(attractionData
.getHtmlAttributionsLink());
htmlAttributionsLink.setTag(attractionData);
htmlAttributionsLink.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
AttractionData data = (AttractionData) ((TextView) v)
.getTag();
utils.openWebURL(v.getContext(),
data.getHtmlAttributionsUrl());
new Intent(Intent.ACTION_VIEW);
return true;
}
});
} else {
htmllayout.setVisibility(View.GONE);
}
// ********************************************* changing for showing
// the zagat review and price level
String priceTag = attractionData.getPriceTag();
String zagatReview = attractionData.getZagatReview();
Log.d(TAG, "Extra Parameter Setup : " + attractionData.getfName()
+ " URL : " + attractionData.getReviewUrl());
Log.d(TAG, "Extra Parameter Setup : priceTag : " + priceTag
+ " zagatReview : " + zagatReview);
if (priceTag != null && !priceTag.equals("")) {
((TextView) view.findViewById(R.id.pricelevelvalue))
.setText(priceTag);
} else {
view.findViewById(R.id.pricelevelvalue).setVisibility(View.GONE);
}
if (zagatReview != null && !zagatReview.equals("")) {
view.findViewById(R.id.moredetail_review).setVisibility(
View.VISIBLE);
((TextView) view.findViewById(R.id.zagatreviewvalue))
.setText(zagatReview);
} else {
view.findViewById(R.id.moredetail_review).setVisibility(View.GONE);
}
Reservation reservation = attractionData.getReservation();
List<PlaceMenu> menus = attractionData.getMenu();
if ((reservation != null) || (menus != null && !menus.isEmpty())) {
view.findViewById(R.id.moredetail_menu_reservation).setVisibility(
View.VISIBLE);
TextView reservationTextView = (TextView) view
.findViewById(R.id.reservationvalues);
if (reservation != null && reservation.getName() != null
&& !reservation.getName().equals("")) {
Log.d(TAG,
"Extra Parameter Setup : reservation "
+ reservation.getName() + " URL : "
+ reservation.getUrl());
view.findViewById(R.id.reservation).setVisibility(View.VISIBLE);
reservationTextView.setVisibility(View.VISIBLE);
reservationTextView.setText(reservation.getName());
reservationTextView.setTag(reservation.getUrl());
reservationTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
utils.openWebURL(v.getContext(),
(String) ((TextView) v).getTag());
new Intent(Intent.ACTION_VIEW);
return true;
}
});
} else {
view.findViewById(R.id.reservation).setVisibility(View.GONE);
reservationTextView.setVisibility(View.GONE);
}
TextView placemenuTextView = (TextView) view
.findViewById(R.id.placemenu);
if (menus != null && !menus.isEmpty()) {
Log.d(TAG,
"Extra Parameter Setup : Menu Size : " + menus.size());
placemenuTextView.setVisibility(View.VISIBLE);
placemenuTextView.setTag(menus);
placemenuTextView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
List<PlaceMenu> placeMenu = (List<PlaceMenu>) ((TextView) v).getTag();
ArrayList<DialogData> data = new ArrayList<DialogData>();
for (int i = 0; i < placeMenu.size(); i++) {
DialogData dialogData = new DialogData();
dialogData.setName(placeMenu.get(i).getName());
dialogData.setValue(placeMenu.get(i).getUrl());
dialogData.setType("url");
data.add(dialogData);
}
utils.showPopupDailog(v.getContext(), data, "Menu");
new Intent(Intent.ACTION_VIEW);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
} else {
placemenuTextView.setVisibility(View.GONE);
}
} else {
view.findViewById(R.id.moredetail_menu_reservation).setVisibility(
View.GONE);
}
if (attractionData.getHotelReview() != null) {
PlaceHotelReview hotelReview = null;
TextView textView = null;
textView = (TextView) view.findViewById(R.id.hotelreviewtext);
if (menuId != null && menuId.equals(Constants.menuHotelId)) {
textView.setText(R.string.hotelPricing);
} else {
textView.setText(R.string.hotelreview);
}
Log.d(TAG, "Hotel Review Step 02 : ");
LinearLayout rl = (LinearLayout) view
.findViewById(R.id.hotelreview);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
view.findViewById(R.id.hotelreview).setVisibility(View.VISIBLE);
rl.removeAllViews();
rl.addView(textView, lp);
for (int i = 0; i < attractionData.getHotelReview().size(); i++) {
hotelReview = attractionData.getHotelReview().get(i);
Log.d(TAG, "Hotel Review Step 03 : " + hotelReview);
textView = new TextView(activity);
Log.d(TAG, "Hotel Review Step 04 : " + hotelReview.getName());
Log.d(TAG, "Hotel Review Step 05 : " + hotelReview.getReviews());
textView.setText(hotelReview.getName().replaceAll("\"", ""));
if (i == attractionData.getHotelReview().size() - 1) {
textView.setPadding(5, 5, 0, 5);
} else if (i == attractionData.getHotelReview().size() - 1) {
textView.setPadding(5, 0, 0, 5);
} else {
textView.setPadding(5, 5, 0, 0);
}
textView.setTextColor(Color.parseColor("#0000ff"));
textView.setTag(hotelReview);
Log.d(TAG, "Hotel Review Step 05 : ");
textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
PlaceHotelReview hotelReview = (PlaceHotelReview) v.getTag();
utils.openWebURL(v.getContext(), hotelReview.getUrl().replaceAll("\"", ""));
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
rl.addView(textView, lp);
}
} else {
view.findViewById(R.id.hotelreview).setVisibility(View.GONE);
}
TextView openCloseTime = (TextView) view
.findViewById(R.id.openclosedesc);
if (attractionData.getOpenCloseDesc() != null
&& !attractionData.getOpenCloseDesc().equals("")
&& !attractionData.getOpenCloseDesc().equalsIgnoreCase("null")) {
openCloseTime.setText(attractionData.getOpenCloseDesc());
} else {
openCloseTime.setVisibility(View.GONE);
}
itemlayer.setOnTouchListener(new DetectMotion(activity, isAddressBook));
if (position % 2 == 0)
view.setBackgroundResource(R.drawable.listshape);
else
view.setBackgroundResource(R.drawable.favoritebody);
return view;
}
private void focusLication(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
AttractionData ad = (AttractionData) v.getTag();
Constants.isMaptobeLoaded = true;
if (ad.getLatitude() != 0 && ad.getLongitude() != 0) {
if (Constants.isDefineNeighbourHood) {
if (Constants.focusLocationNH == null) {
Constants.focusLocationNH = new Location("");
}
Constants.focusLocationNH.setLatitude(ad.getLatitude());
Constants.focusLocationNH.setLongitude(ad.getLongitude());
if (Constants.myNeighborHoodLocation == null) {
Constants.myNeighborHoodLocation = new Location("");
}
Constants.myNeighborHoodLocation.setLatitude(ad
.getLatitude());
Constants.myNeighborHoodLocation.setLongitude(ad
.getLongitude());
} else {
if (Constants.focusLocation == null) {
Constants.focusLocation = new Location("");
}
Constants.focusLocation.setLatitude(ad.getLatitude());
Constants.focusLocation.setLongitude(ad.getLongitude());
}
activity.finish();
if (isAddressBook) {
Constants.isPABImportant = true;
activity.overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_left);
} else {
Constants.isPABImportant = false;
activity.overridePendingTransition(R.anim.slide_out_right,
R.anim.slide_in_right);
}
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
}
Any help is appreciated.

Try like this way
list.clear();
adpater.notifyDataSetChanged();
/// remove item from list.
adapter.clear();
adpater.notifyDataSetChanged();
Not all Adapters have a clear() method. ArrayAdapter does, but ListAdapter or SimpleAdapter doesn't

Just notify the listview after clearing the data of adapter i guess searchAdapter is your adapter . SearchAdapter is a custom adapter where you need to clear data based on type of adapter then call notifyDataSetChanged.

This is the code for clearing listview data on button click
Button yourbutton; // init it
yourButon.setOnClickListener(new OnClickListener(){
yourList.clear(); // this list which you hava passed in Adapter for your listview
yourAdapter.notifyDataSetChanged(); // notify to listview for refresh
});

Related

Getting ArrayIndexOutofBoundsException in android listview

I am using listview to load data from sqlite when i open the app i could see the following error can anyone tell me what i am doing wrong in the adapter.Even when the app gets started it shows the following error
Database:
public ArrayList<Daybook> getAlldaybookentriesdatewise(int s) {
ArrayList<Daybook> daybookDetails = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0) as amountout,daybookusertype FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT " + s + "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookDetails.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return daybookDetails;
}
Activity:
public class NewDaybook_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ListView listview;
FloatingActionButton fabaddnew;
LinearLayout emptyy;
DatabaseHandler databasehandler;
ArrayList<Daybook> daybookcashentries;
Daybook_adapter dadapter;
LoginSession loginSession;
boolean loadingMore = false;
String totaldaybookcount;
int olimit = 2;
int totalcount;
String s;
private Locale mLocale;
private final String[] language = {"en", "ta"};
LinearLayout li_farmer, li_worker, li_vehicle, li_otherexpense, li_buyer, li_general;
RadioGroup rg_filtering;
RadioButton rbtn_farmertrade, rbtn_farmeradvance, rbtn_work, rbtn_workadvance, rbtn_groupwork, rbtn_groupadvance, rbtn_vehicle, rbtn_otherexpense;
AlertDialog alert;
ImageView img_farm, img_buy, img_work, img_veh, img_expense;
TextView tv_farm, tv_buy, tv_work, tv_veh, tv_expense;
public static final int progress_bar_type = 0;
private ProgressDialog pDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_daybooks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.daybook);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
TextView tv_balanceamt = (TextView) header.findViewById(R.id.nav_name);
TextView tv_timedate = (TextView) header.findViewById(R.id.tv_dateandtime);
tv_balanceamt.setTextSize(22);
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy ");
String dateString = sdf.format(date);
tv_timedate.setText(dateString);
databasehandler = new DatabaseHandler(getApplicationContext());
String balanceamount = String.valueOf(databasehandler.getdaybookbalanceamt());
Log.e("daybookbalanceamt", String.valueOf(balanceamount));
balanceamount = balanceamount.replaceAll("[\\[\\](){}]", "");
tv_balanceamt.setText("\u20B9" + balanceamount);
initalize();
}
private void initalize() {
loginSession = new LoginSession(getApplicationContext());
loginSession.checkLogin();
databasehandler = new DatabaseHandler(getApplicationContext());
listview = (ListView) findViewById(R.id.list_daybook);
li_general = (LinearLayout) findViewById(R.id.linearLayout2);
li_farmer = (LinearLayout) findViewById(R.id.linear_farmer);
li_worker = (LinearLayout) findViewById(R.id.linear_worker);
li_vehicle = (LinearLayout) findViewById(R.id.linear_vehicle);
li_otherexpense = (LinearLayout) findViewById(R.id.linear_otherexpense);
li_buyer = (LinearLayout) findViewById(R.id.linear_buyers);
fabaddnew = (FloatingActionButton) findViewById(R.id.addnewtransaction);
emptyy = (LinearLayout) findViewById(R.id.empty);
rg_filtering = (RadioGroup) findViewById(R.id.rg_sortdata);
rbtn_farmertrade = (RadioButton) findViewById(R.id.rbtn_farmers);
rbtn_farmeradvance = (RadioButton) findViewById(R.id.rbtn_fadvance);
rbtn_work = (RadioButton) findViewById(R.id.rbtn_work);
rbtn_workadvance = (RadioButton) findViewById(R.id.rbtn_workadvance);
rbtn_groupwork = (RadioButton) findViewById(R.id.rbtn_groupwork);
rbtn_groupadvance = (RadioButton) findViewById(R.id.rbtn_groupadvance);
rbtn_vehicle = (RadioButton) findViewById(R.id.rbtn_vehicle);
rbtn_otherexpense = (RadioButton) findViewById(R.id.rbtn_otherexpense);
img_farm = (ImageView) findViewById(R.id.img_farmer);
img_buy = (ImageView) findViewById(R.id.img_buyer);
img_work = (ImageView) findViewById(R.id.img_worker);
img_veh = (ImageView) findViewById(R.id.img_vehicle);
img_expense = (ImageView) findViewById(R.id.img_otherexpense);
tv_farm = (TextView) findViewById(R.id.tv_farmer);
tv_buy = (TextView) findViewById(R.id.tv_buyer);
tv_work = (TextView) findViewById(R.id.tv_worker);
tv_veh = (TextView) findViewById(R.id.tv_vehicle);
tv_expense = (TextView) findViewById(R.id.tv_otherexpense);
listview.setFastScrollEnabled(true);
new Daybooklistloader().execute();
li_buyer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
// When you Touch Down
// U can change Text and Image As per your Functionality
li_buyer.setBackgroundColor(Color.parseColor("#FF4081"));
tv_buy.setTextColor(Color.parseColor("#FFFFFF"));
img_buy.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
break;
case MotionEvent.ACTION_UP:
//When you Release the touch
// U can change Text and Image As per your Functionality
startActivity(new Intent(NewDaybook_Activity.this, Activity_BuyerTransaction.class));
NewDaybook_Activity.this.finish();
break;
}
return true;
}
});
li_farmer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
// When you Touch Down
// U can change Text and Image As per your Functionality
li_farmer.setBackgroundColor(Color.parseColor("#FF4081"));
tv_farm.setTextColor(Color.parseColor("#FFFFFF"));
img_farm.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
NewDaybook_Activity.this.finish();
break;
case MotionEvent.ACTION_UP:
//When you Release the touch
// U can change Text and Image As per your Functionality
startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
NewDaybook_Activity.this.finish();
break;
}
return true;
}
});
fabaddnew.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
fabaddnew.setRippleColor(R.drawable.ripple_effect);
startActivity(new Intent(NewDaybook_Activity.this, Activity_AddFastEntryDaybook.class));
NewDaybook_Activity.this.finish();
return true;
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
startActivity(new Intent(NewDaybook_Activity.this, NewDaybook_Activity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_dashboard) {
startActivity(new Intent(NewDaybook_Activity.this, DashboardActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_buyer) {
startActivity(new Intent(NewDaybook_Activity.this, BuyerListActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_farmer) {
startActivity(new Intent(NewDaybook_Activity.this, FarmerlistActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_workers) {
startActivity(new Intent(NewDaybook_Activity.this, WorkerListActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_vehicles) {
startActivity(new Intent(NewDaybook_Activity.this, VehicleList_activity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_otherexpense) {
startActivity(new Intent(NewDaybook_Activity.this, OtherExpenseList.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_report) {
startActivity(new Intent(NewDaybook_Activity.this, BillBookActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_settings) {
// startActivity(new Intent(NewDaybook_Activity.this, SettingsActivity.class));
// NewDaybook_Activity.this.finish();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.language)
.setItems(R.array.language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setLocale(language[i]);
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (id == R.id.nav_logout) {
loginSession.logoutUser();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setLocale(String lang) {
Log.d("Selected Language is ", lang);
SharedPreferences preferences = getSharedPreferences(MyApplication.PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(MyApplication.PREF_USER_LANGUAGE_KEY, lang).apply();
mLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(mLocale);
}
res.updateConfiguration(conf, dm);
recreate();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
private class Daybooklistloader extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... strings) {
daybookcashentries = new ArrayList<Daybook>();
daybookcashentries = databasehandler.getAlldaybookentriesdatewise(olimit);
return null;
}
#Override
protected void onPostExecute(String j) {
dismissDialog(progress_bar_type);
View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_footer, null, false);
listview.addFooterView(footerView);
dadapter = new Daybook_adapter(NewDaybook_Activity.this, daybookcashentries);
if (dadapter != null) {
if (dadapter.getCount() > 0) {
emptyy.setVisibility(View.INVISIBLE);
listview.setAdapter(dadapter);
}
} else {
emptyy.setVisibility(View.VISIBLE);
}
final List<String> labels = databasehandler.getTotaldaybookrecord();
for (String s : labels) {
totaldaybookcount = s;
}
totalcount = Integer.parseInt(totaldaybookcount);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = fabaddnew.getScrollY();
int li_initPosY = li_general.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
dadapter.isScrolling(true);
fabaddnew.animate().cancel();
li_general.animate().cancel();
fabaddnew.animate().translationYBy(150);
li_general.animate().translationYBy(150);
} else {
dadapter.isScrolling(false);
fabaddnew.animate().cancel();
li_general.animate().cancel();
fabaddnew.animate().translationY(btn_initPosY);
li_general.animate().translationY(li_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
dadapter.isScrolling(true);
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already? Load more!
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadDataTask().execute();
}
}
});
}
}
private class LoadDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingMore = true;
// showDialog(progress_bar_type);
}
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
Log.e("test2", "reached");
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Log.e("test3", "starting");
databasehandler = new DatabaseHandler(getApplicationContext());
if (olimit > totalcount) {
// olimit = 1;
// olimit = 2;
} else {
olimit = olimit + 1;
}
daybookcashentries = new ArrayList<Daybook>();
databasehandler = new DatabaseHandler(getApplicationContext());
daybookcashentries = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0),daybookusertype as amountout FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT '" + olimit + "'";
SQLiteDatabase db = databasehandler.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookcashentries.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
dadapter.setTransactionList(daybookcashentries);
loadingMore = false;
// dismissDialog(progress_bar_type);
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
loadingMore = false;
}
}
}
Adapter:
public class Daybook_adapter extends BaseAdapter {
Context context;
private ArrayList<Daybook> entriesdaybook;
private ArrayList<Daybooklist> daybooklists = new ArrayList<Daybooklist>();
private boolean isListScrolling;
private LayoutInflater inflater;
public Daybook_adapter(Context context, ArrayList<Daybook> entriesdaybook) {
this.context = context;
this.entriesdaybook = entriesdaybook;
}
#Override
public int getCount() {
return entriesdaybook.size();
}
#Override
public Object getItem(int i) {
return entriesdaybook.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.model_daybook, null);
final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
final TextView tv_totalamt = (TextView) convertView.findViewById(R.id.daybook_total_amt);
final ImageView img_pdf = (ImageView) convertView.findViewById(R.id.img_printpdf);
LinearLayout emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
ExpandableHeightListView daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);
final Daybook m = entriesdaybook.get(position);
String s = m.getDate();
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String date = spiliter[2];
if (month.startsWith("01")) {
tv_date.setText(date + "Jan" + year);
} else if (month.startsWith("02")) {
tv_date.setText(date + "Feb" + year);
} else if (month.startsWith("03")) {
tv_date.setText(date + "Mar" + year);
} else if (month.startsWith("04")) {
tv_date.setText(date + "Apr" + year);
} else if (month.startsWith("05")) {
tv_date.setText(date + "May" + year);
} else if (month.startsWith("06")) {
tv_date.setText(date + "Jun" + year);
} else if (month.startsWith("07")) {
tv_date.setText(date + "Jul" + year);
} else if (month.startsWith("08")) {
tv_date.setText(date + "Aug" + year);
} else if (month.startsWith("09")) {
tv_date.setText(date + "Sep" + year);
} else if (month.startsWith("10")) {
tv_date.setText(date + "Oct" + year);
} else if (month.startsWith("11")) {
tv_date.setText(date + "Nov" + year);
} else if (month.startsWith("12")) {
tv_date.setText(date + "Dec" + year);
}
tv_cashin.setText("\u20B9" + m.getCashin());
tv_cashout.setText("\u20B9" + m.getCashout());
double one = Double.parseDouble(m.getCashin());
double two = Double.parseDouble(m.getCashout());
double three = one + two;
tv_totalamt.setText("\u20B9" + String.valueOf(three));
/* DatabaseHandler databaseHandler = new DatabaseHandler(context);
daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
for (int i = 0; i < daybooklists.size(); i++) {
try {
Daybooklist_adapter adapter = new Daybooklist_adapter(context, daybooklists);
if (adapter != null) {
if (adapter.getCount() > 0) {
emptyy.setVisibility(View.GONE);
daybookdetailviewlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} else {
daybookdetailviewlist.setEmptyView(emptyy);
}
daybookdetailviewlist.setExpanded(true);
daybookdetailviewlist.setFastScrollEnabled(true);
if (!isListScrolling) {
img_pdf.setEnabled(false);
adapter.isScrolling(true);
} else {
img_pdf.setEnabled(true);
adapter.isScrolling(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}*/
img_pdf.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage("Click yes to Print Report for : " + m.getDate())
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent pdfreport = new Intent(context, Activity_Daybookpdf.class);
pdfreport.putExtra("date", m.getDate());
context.startActivity(pdfreport);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(context.getResources().getColor(R.color.colorAccent));
Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
pbutton.setPadding(0, 10, 10, 0);
pbutton.setTextColor(Color.WHITE);
return false;
}
});
return convertView;
}
public void setTransactionList(ArrayList<Daybook> newList) {
entriesdaybook = newList;
notifyDataSetChanged();
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("scrollcheck", String.valueOf(isListScrolling));
}
Error:
*** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
The crash logs doesn't seems to be the reason for the crash.
Try cleaning the project and run.
If the issue still exists do disable instant run from the settings and run.
Hope this should get fixes and start running.

OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available

I am having this error while scrolling list view with items.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available
Can anyone help please?
EDIT
public class ItemsListAdapter2 extends BaseAdapter {
private final float NUMBER_OF_ITEMS_PER_GRID = 2;
private final int AD_POSITION = 4;
private Context context;
private ArrayList<ArrayList<ItemResponse>> allData = new ArrayList<ArrayList<ItemResponse>>();
public class ViewHolder {
// for Item1
LinearLayout itemLayout1;
ImageView itemImage1;
TextView itemDate1;
ImageView itemTagImage1;
TextView normalItemPrice1;
TextView pinnedItemPrice1;
TextView itemTitle1;
TextView itemDescription1;
// for Item2
LinearLayout itemLayout2;
ImageView itemImage2;
TextView itemDate2;
ImageView itemTagImage2;
TextView normalItemPrice2;
TextView pinnedItemPrice2;
TextView itemTitle2;
TextView itemDescription2;
RelativeLayout adLayout;
ImageView adUnit;
}
public ItemsListAdapter2(Context context, ArrayList<ItemResponse> data) {
this.context = context;
setData(data);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_listings2, null);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemLayout1 = (LinearLayout) convertView.findViewById(R.id.item1_layout);
holder.itemImage1 = (ImageView) convertView.findViewById(R.id.item_image1);
holder.itemDate1 = (TextView) convertView.findViewById(R.id.item_date1);
holder.itemTagImage1 = (ImageView) convertView.findViewById(R.id.tag_image1);
holder.normalItemPrice1 = (TextView) convertView.findViewById(R.id.normal_item_price1);
holder.pinnedItemPrice1 = (TextView) convertView.findViewById(R.id.pinned_item_price1);
holder.itemTitle1 = (TextView) convertView.findViewById(R.id.item_title1);
holder.itemDescription1 = (TextView) convertView.findViewById(R.id.item_description1);
holder.itemLayout2 = (LinearLayout) convertView.findViewById(R.id.item2_layout);
holder.itemImage2 = (ImageView) convertView.findViewById(R.id.item_image2);
holder.itemDate2 = (TextView) convertView.findViewById(R.id.item_date2);
holder.itemTagImage2 = (ImageView) convertView.findViewById(R.id.tag_image2);
holder.normalItemPrice2 = (TextView) convertView.findViewById(R.id.normal_item_price2);
holder.pinnedItemPrice2 = (TextView) convertView.findViewById(R.id.pinned_item_price2);
holder.itemTitle2 = (TextView) convertView.findViewById(R.id.item_title2);
holder.itemDescription2 = (TextView) convertView.findViewById(R.id.item_description2);
holder.adLayout = (RelativeLayout) convertView.findViewById(R.id.banner_ad);
holder.adUnit = (ImageView) convertView.findViewById(R.id.ad_view_image);
if (allData.get(position) != null && allData.get(position).size() > 0) {
setItem1Data(holder, position);
setItem2Data(holder, position);
}
if ((position + 1) % AD_POSITION == 0) {
// show ad
holder.adLayout .setVisibility(View.VISIBLE);
//initializeBannerAd(convertView, holder.adUnit);
} else {
holder.adLayout .setVisibility(View.GONE);
}
return convertView;
}
#Override
public int getCount() {
return allData.size();
}
#Override
public Object getItem(int position) {
try {
return allData.get(position);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
#Override
public long getItemId(int position) {
try {
return allData.indexOf(getItem(position));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return -1;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
private void initData (ArrayList<ItemResponse> data) {
int numberOfItems = (int) Math.ceil(data.size() / NUMBER_OF_ITEMS_PER_GRID);
ArrayList<ArrayList<ItemResponse>> tempData = new ArrayList<ArrayList<ItemResponse>>(numberOfItems);
for (int i = 0; i < numberOfItems; i++) {
ArrayList<ItemResponse> items = new ArrayList<ItemResponse>();
for (int j = 0; j < NUMBER_OF_ITEMS_PER_GRID; j++) {
try {
items.add(data.get(j));
} catch (Exception e) {
e.printStackTrace();
}
}
tempData.add(i, items);
// clear
data.removeAll(items);
}
for (int n = 0; n < tempData.size(); n++) {
allData.add(tempData.get(n));
}
}
public void setData (ArrayList<ItemResponse> data) {
allData.clear();
ArrayList<ItemResponse> mData = new ArrayList<ItemResponse>();
for (int i = 0; i < data.size(); i++) {
mData.add(data.get(i));
}
initData(mData);
}
public void setItem1Data (ViewHolder holder , int position) {
try {
holder.itemLayout1.setVisibility(View.VISIBLE);
final ItemResponse current = allData.get(position).get(0);
if (current != null) {
if (current.getId() == ForSaleConstants.POST_AD_LISTING_ID) {
String postAdPlaceholder = "";
ForSaleApplication app = (ForSaleApplication) context.getApplicationContext();
if (app.getDefaultLocale().toLowerCase().startsWith(ForSaleConstants.ARABIC_LANGUAGE)) {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_AR_URL_KEY);
} else {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_EN_URL_KEY);
}
if (PhoneUtils.isEmpty(postAdPlaceholder) == false) {
PhoneUtils.setImage(context, holder.itemImage1, postAdPlaceholder);
}
holder.itemDate1.setVisibility(View.GONE);
holder.itemTagImage1.setVisibility(View.GONE);
holder.normalItemPrice1.setVisibility(View.GONE);
holder.pinnedItemPrice1.setVisibility(View.GONE);
holder.itemTitle1.setVisibility(View.GONE);
holder.itemDescription1.setVisibility(View.GONE);
// TODO handle on click listener for placeholder.
} else {
holder.itemDate1.setVisibility(View.VISIBLE);
holder.itemTagImage1.setVisibility(View.VISIBLE);
holder.itemTitle1.setVisibility(View.VISIBLE);
holder.itemDescription1.setVisibility(View.VISIBLE);
if (current.getImages() != null && current.getImages().size() > 0) {
PhoneUtils.setImage(context, holder.itemImage1, current.getImages().get(0));
}
holder.itemDate1.setText(current.getDatePublished());
if (current.isPinned() == true) {
holder.itemTagImage1.setImageResource(R.drawable.tag_pinned);
}
if (current.isPinned() == true) {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.pinnedItemPrice1.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.pinnedItemPrice1.setText("" + current.getAskingPrice());
holder.normalItemPrice1.setVisibility(View.GONE);
holder.pinnedItemPrice1.setVisibility(View.VISIBLE);
holder.itemTagImage1.setVisibility(View.VISIBLE);
} else {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.normalItemPrice1.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.normalItemPrice1.setText("" + current.getAskingPrice());
holder.normalItemPrice1.setVisibility(View.VISIBLE);
holder.pinnedItemPrice1.setVisibility(View.GONE);
holder.itemTagImage1.setVisibility(View.GONE);
}
holder.itemTitle1.setText(current.getTitle());
holder.itemDescription1.setText(current.getDescription());
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ItemDetailsActivity.class);
intent.putExtra(ForSaleConstants.ACTIVITY_ITEM_OBJECT, current);
context.startActivity(intent);
}
};
holder.itemImage1.setOnClickListener(clickListener);
holder.itemTitle1.setOnClickListener(clickListener);
holder.itemDescription1.setOnClickListener(clickListener);
}
}
} catch (Exception e) {
e.printStackTrace();
holder.itemLayout1.setVisibility(View.INVISIBLE);
}
}
public void setItem2Data (ViewHolder holder , int position) {
try {
holder.itemLayout2.setVisibility(View.VISIBLE);
final ItemResponse current = allData.get(position).get(1);
if (current != null) {
if (current.getId() == ForSaleConstants.POST_AD_LISTING_ID) {
String postAdPlaceholder = "";
ForSaleApplication app = (ForSaleApplication) context.getApplicationContext();
if (app.getDefaultLocale().toLowerCase().startsWith(ForSaleConstants.ARABIC_LANGUAGE)) {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_AR_URL_KEY);
} else {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_EN_URL_KEY);
}
if (PhoneUtils.isEmpty(postAdPlaceholder) == false) {
PhoneUtils.setImage(context, holder.itemImage2, postAdPlaceholder);
} else {
PhoneUtils.setImage(context, holder.itemImage2, null, R.drawable.placeholder_squre);
}
holder.itemDate2.setVisibility(View.GONE);
holder.itemTagImage2.setVisibility(View.GONE);
holder.normalItemPrice2.setVisibility(View.GONE);
holder.pinnedItemPrice2.setVisibility(View.GONE);
holder.itemTitle2.setVisibility(View.GONE);
holder.itemDescription2.setVisibility(View.GONE);
// TODO handle on click listener for placeholder.
} else {
holder.itemDate2.setVisibility(View.VISIBLE);
holder.itemTagImage2.setVisibility(View.VISIBLE);
holder.itemTitle2.setVisibility(View.VISIBLE);
holder.itemDescription2.setVisibility(View.VISIBLE);
if (current.getImages() != null && current.getImages().size() > 0) {
PhoneUtils.setImage(context, holder.itemImage2, current.getImages().get(0));
}
holder.itemDate2.setText(current.getDatePublished());
if (current.isPinned() == true) {
holder.itemTagImage2.setImageResource(R.drawable.tag_pinned);
} else {
holder.itemTagImage2.setImageResource(R.drawable.tag);
}
if (current.isPinned() == true) {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.pinnedItemPrice2.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.pinnedItemPrice2.setText("" + current.getAskingPrice());
holder.normalItemPrice2.setVisibility(View.GONE);
holder.pinnedItemPrice2.setVisibility(View.VISIBLE);
holder.itemTagImage2.setVisibility(View.VISIBLE);
} else {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.normalItemPrice2.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.normalItemPrice2.setText("" + current.getAskingPrice());
holder.normalItemPrice2.setVisibility(View.VISIBLE);
holder.pinnedItemPrice2.setVisibility(View.GONE);
holder.itemTagImage2.setVisibility(View.GONE);
}
holder.itemTitle2.setText(current.getTitle());
holder.itemDescription2.setText(current.getDescription());
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ItemDetailsActivity.class);
intent.putExtra(ForSaleConstants.ACTIVITY_ITEM_OBJECT, current);
context.startActivity(intent);
}
};
holder.itemImage2.setOnClickListener(clickListener);
holder.itemTitle2.setOnClickListener(clickListener);
holder.itemDescription2.setOnClickListener(clickListener);
}
}
} catch (Exception e) {
e.printStackTrace();
holder.itemLayout2.setVisibility(View.INVISIBLE);
}
}
}
and also find the loading method, I am implementing on scroll load more items
private void loadData (boolean inBackground) {
int categoryId = -1;
if (mParentCategory != null)
categoryId = mParentCategory.getId();
mIsInBackground = inBackground;
if (mIsInBackground == false)
showProgressDialog();
else
disableBackButton();
// TODO districts.
ForSaleServerManager.getInstance().getListings(this, mSearchQuery,
categoryId, -1, mSellingTypeId, mPageNumber, this);
}
and in the following is setting data in the adapter
if (mPageNumber == 1) {
// add all pinning items.
if (items.getPinnedItems() != null && items.getPinnedItems().size() > 0)
allItems.addAll(items.getPinnedItems());
if (mMode == MODE_SEARCH) {
// handle post ad listing item.
if ((allItems.size() % 2) != 0)
allItems.add(new ItemResponse(ForSaleConstants.POST_AD_LISTING_ID));
}
}
// add all normal items.
if (items.getNormalItems() != null && items.getNormalItems().size() > 0)
for (int i = 0; i < items.getNormalItems().size(); i++) {
if (allItems.contains(items.getNormalItems().get(i)) == false)
allItems.add(items.getNormalItems().get(i));
}
if (allItems != null && allItems.size() > 0) {
if (mAdapter == null) {
mAdapter = new ItemsListAdapter2(ItemsActivity.this, allItems);
mListView.setAdapter(mAdapter);
mListView.setVisibility(View.VISIBLE);
mNoDataFound.setVisibility(View.GONE);
} else {
mAdapter.setData(allItems);
mAdapter.notifyDataSetChanged();
mListView.setVisibility(View.VISIBLE);
mNoDataFound.setVisibility(View.GONE);
}
} else {
mListView.setVisibility(View.GONE);
mNoDataFound.setVisibility(View.VISIBLE);
showNoData(R.drawable.icon_listing_unselected, R.string.error_categories_found);
}

Android Custom Keyboard stuck When Swapping to/from Another Keyboard

I'm developing a custom keyboard for Android that will store login credentials in a local database (plan is to encrypt the DB after the thing works flawlessly).
The keyboard has a basic layout with a KeyboardView at the bottom and a 'Switch Keyboard' button at the top-right corner.
Everything works fine except that when i click the switch button, things start to fail.
Scenario:
1) My keyboard is active and everything is fine. Keyboard visibility is managed by the system.
2) I click the switch button, my keyboard is closed and previously enabled keyboard is displayed.
3) Now i open the Keyboard Chooser through Notification Tray and re-enable my custom keyboard.
My keyboard is set as default, but there's no keyboard on the screen. when i touch the bottom half of screen area where keyboard appears, the characters are being typed (yes, my keyboard is there but is invisible!).
I press the Back key on my phone and the system doesn't close the keyboard and it's stuck there.
I press the Home key and the keyboard becomes visible for a few milliseconds, is closed by the system and i'm sent to the Home Screen.
I've tried waiting for the keyboard to appear, etc. and also tried the app on 3 other phones from different make. Also, i'm developing the app for Lollipop (API 21 and higher).
Here's the code:
1) InputMethodService:
public class HomlesInputService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
CustomKeyboardView kv;
Keyboard qwertyKeyboard, symbolKeyboard;
Boolean caps;
private String myPwd, myUid;
SharedPreferences mPrefs;
SharedPreferences.Editor mEdit;
Boolean isPassword, isUid, uidFilled, pwdFilled;
Vibrator vibrator;
View keyboard;
EditorInfo sEditorInfo;
SQLiteDatabase db;
InputMethodManager imm;
IBinder token;
String defImeId;
public static final int SYM_KEYBOARD = -10;
public static final int GO_BUTTON = -4;
public static final double GO_BUTTON_ASPECT_RATIO = 1.88;
public static final double NEXT_BUTTON_ASPECT_RATIO = 1;
public HomlesInputService() {
}
#Override
public void onCreate() {
super.onCreate();
mPrefs = getSharedPreferences(Constants.APP_PREFS, MODE_PRIVATE);
mEdit = mPrefs.edit();
//storing ime id in prefs
String myId = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
mEdit.putString(Constants.MY_IME_ID, myId);
mEdit.commit();
imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
defImeId = mPrefs.getString(Constants.DEFAULT_KEYBOARD, null); //the id of previous IME stored in preferences (found correct in debugging)
qwertyKeyboard = new Keyboard(this, R.xml.qwerty_keyboard_layout);
symbolKeyboard = new Keyboard(this, R.xml.symbol_keyboard_layout);
db = openOrCreateDatabase(DbConstants.DATABASE_NAME, MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS " + DbConstants.TABLE_NAME + "("
+ DbConstants.APP_ID + "," + DbConstants.UID_VALUE + "," + DbConstants.PWD_VALUE + ")");
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
}
#Override
public View onCreateInputView() {
keyboard = getLayoutInflater().inflate(R.layout.my_custom_keyboard, null);
ImageView ivRevertKeyboard = (ImageView) keyboard.findViewById(R.id.ivRevertKeyboard); //this button is used to switch to previous IME
token = this.getWindow().getWindow().getAttributes().token;
if (defImeId != null) {
ivRevertKeyboard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(Constants.VIBRATE_TIME_MEDIUM);
try {
imm.hideSoftInputFromInputMethod(token, 0);
imm.setInputMethod(token, defImeId);
} catch (Throwable t) { // java.lang.NoSuchMethodError if API_level<11
t.printStackTrace();
}
}
});
} else {
ivRevertKeyboard.setVisibility(View.GONE);
}
kv = (CustomKeyboardView) keyboard.findViewById(R.id.keyboard);
kv.setKeyboard(qwertyKeyboard);
kv.setOnKeyboardActionListener(this);
caps = false;
myPwd = "";
myUid = "";
isPassword = false;
return keyboard;
}
#Override
public void onStartInputView(EditorInfo info, boolean restarting) {
sEditorInfo = info;
uidFilled = false;
pwdFilled = false;
if (info.inputType == 129) {
isPassword = true;
} else {
isPassword = false;
}
CharSequence CHARbeforeCursor = getCurrentInputConnection().getTextBeforeCursor(999, 0);
CharSequence CHARafterCursor = getCurrentInputConnection().getTextAfterCursor(999, 0);
if (CHARbeforeCursor != null && CHARafterCursor != null) {
String beforeCursor = CHARbeforeCursor.toString();
String afterCursor = CHARafterCursor.toString();
if (isPassword) {
myPwd = beforeCursor + afterCursor;
} else {
myUid = beforeCursor + afterCursor;
}
}
setGoButton();
}
private void setGoButton() {
List<Keyboard.Key> keys = kv.getKeyboard().getKeys();
Drawable dr;
int rowHeight, goBtWidth = 0, nextBtWidth = 0;
rowHeight = Utils.dpToPx(40, getApplicationContext());
goBtWidth = Integer.parseInt("" + Math.round(rowHeight * GO_BUTTON_ASPECT_RATIO));
nextBtWidth = Integer.parseInt("" + Math.round(rowHeight * NEXT_BUTTON_ASPECT_RATIO));
for (int i = 0; i < keys.size(); i++) {
Keyboard.Key key = keys.get(i);
int code = key.codes[0];
if (code == GO_BUTTON) {
if (isPassword) {
key.width = goBtWidth;
dr = getResources().getDrawable(R.drawable.keyboard_save_and_go, getApplicationContext().getTheme());
} else {
key.width = nextBtWidth;
dr = getResources().getDrawable(R.drawable.keyboard_next, getApplicationContext().getTheme());
}
key.icon = dr;
}
}
}
#Override
public void onPress(int primaryCode) {
vibrator.vibrate(Constants.VIBRATE_TIME_SHORT);
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
kv.setPreviewEnabled(false);
break;
case Keyboard.KEYCODE_SHIFT:
kv.setPreviewEnabled(false);
break;
case Keyboard.KEYCODE_DONE:
kv.setPreviewEnabled(false);
break;
case SYM_KEYBOARD:
kv.setPreviewEnabled(false);
break;
case 32:
kv.setPreviewEnabled(false);
break;
default:
kv.setPreviewEnabled(true);
}
}
#Override
public void onRelease(int i) {
}
#Override
public void onKey(int primaryCode, int[] ints) {
InputConnection conn = getCurrentInputConnection();
uidFilled = mPrefs.getBoolean(Constants.UID_FILLED, false);
pwdFilled = mPrefs.getBoolean(Constants.PWD_FILLED, false);
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
conn.deleteSurroundingText(1, 0);
if (isPassword) {
if (myPwd.length() > 0) {
String beforeCursor = conn.getTextBeforeCursor(myPwd.length(), 0).toString();
beforeCursor = beforeCursor.substring(0, beforeCursor.length());
String afterCursor = conn.getTextAfterCursor(myPwd.length(), 0).toString();
myPwd = beforeCursor + afterCursor;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_PWD, myPwd);
} else {
mEdit.putString(Constants.NEW_PWD, myPwd);
}
mEdit.commit();
Log.d("##Pwd saved", "" + mPrefs.getString(Constants.NEW_PWD, ""));
}
} else {
if (myUid.length() > 0) {
String beforeCursor = conn.getTextBeforeCursor(myUid.length(), 0).toString();
beforeCursor = beforeCursor.substring(0, beforeCursor.length());
String afterCursor = conn.getTextAfterCursor(myUid.length(), 0).toString();
myUid = beforeCursor + afterCursor;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_UID, myUid);
} else {
mEdit.putString(Constants.NEW_UID, myUid);
}
mEdit.commit();
Log.d("##Uid saved", "" + mPrefs.getString(Constants.NEW_UID, ""));
}
}
break;
case Keyboard.KEYCODE_SHIFT:
caps = !caps;
kv.setShifted(caps);
kv.invalidateAllKeys();
break;
case Keyboard.KEYCODE_DONE:
switch (sEditorInfo.imeOptions & (EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION)) {
case EditorInfo.IME_ACTION_GO:
conn.performEditorAction(EditorInfo.IME_ACTION_GO);
break;
case EditorInfo.IME_ACTION_NEXT:
conn.performEditorAction(EditorInfo.IME_ACTION_NEXT);
break;
case EditorInfo.IME_ACTION_SEARCH:
conn.performEditorAction(EditorInfo.IME_ACTION_SEARCH);
break;
case EditorInfo.IME_ACTION_SEND:
conn.performEditorAction(EditorInfo.IME_ACTION_SEND);
break;
case EditorInfo.IME_ACTION_DONE:
saveCredentialsToDb();
conn.performEditorAction(EditorInfo.IME_ACTION_DONE);
//triggers login
break;
default:
conn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
break;
}
break;
case SYM_KEYBOARD:
Keyboard currentKeyb = kv.getKeyboard();
if (currentKeyb == symbolKeyboard) {
kv.setKeyboard(qwertyKeyboard);
} else {
kv.setKeyboard(symbolKeyboard);
}
setGoButton();
break;
default:
char code = (char) primaryCode;
if (Character.isLetter(code) && caps) {
code = Character.toUpperCase(code);
}
if (isPassword) {
myPwd = myPwd + code;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_PWD, myPwd);
} else {
mEdit.putString(Constants.NEW_PWD, myPwd);
}
mEdit.commit();
Log.d("##Pwd saved", "" + mPrefs.getString(Constants.NEW_PWD, ""));
} else {
myUid = myUid + code;
if (uidFilled && pwdFilled) {
mEdit.putString(Constants.EDIT_NEW_UID, myUid);
} else {
mEdit.putString(Constants.NEW_UID, myUid);
}
mEdit.commit();
Log.d("##Uid saved", "" + mPrefs.getString(Constants.NEW_UID, ""));
}
conn.commitText(String.valueOf(code), 1);
}
}
private void saveCredentialsToDb() {
db = openOrCreateDatabase(DbConstants.DATABASE_NAME, MODE_PRIVATE, null);
String activityDbId = getCurrentInputEditorInfo().packageName;
if (myUid == null || myUid.length() <= 0) {
Toast.makeText(getApplicationContext(), "Enter the Username", Toast.LENGTH_SHORT).show();
return;
} else if (myPwd == null || myPwd.length() <= 0) {
Toast.makeText(getApplicationContext(), "Enter the Password", Toast.LENGTH_SHORT).show();
return;
} else if (activityDbId == null && activityDbId.length() <= 0) {
Toast.makeText(getApplicationContext(), "Failed to get app ID", Toast.LENGTH_SHORT).show();
return;
}
Log.d("##Activity pkg name", "" + activityDbId);
ContentValues cv = new ContentValues();
cv.put(DbConstants.APP_ID, activityDbId);
cv.put(DbConstants.UID_VALUE, myUid);
cv.put(DbConstants.PWD_VALUE, myPwd);
if (uidFilled && pwdFilled) {
String oldUid = mPrefs.getString(Constants.EDIT_OLD_UID, null);
String oldPwd = mPrefs.getString(Constants.EDIT_OLD_PWD, null);
if (oldUid != null && oldPwd != null) {
if (oldUid.contentEquals(myUid) && oldPwd.contentEquals(myPwd)) {
Toast.makeText(getApplicationContext(), "Unchanged values.", Toast.LENGTH_SHORT).show();
return;
}
db.update(DbConstants.TABLE_NAME, cv, DbConstants.APP_ID + "=?" + " AND " + DbConstants.UID_VALUE + "=?", new String[]{activityDbId, oldUid});
mEdit.remove(Constants.EDIT_OLD_UID);
mEdit.remove(Constants.EDIT_NEW_UID);
mEdit.remove(Constants.EDIT_NEW_PWD);
mEdit.putBoolean(Constants.UID_FILLED, false);
mEdit.putBoolean(Constants.PWD_FILLED, false);
mEdit.commit();
uidFilled = false;
pwdFilled = false;
Toast.makeText(getApplicationContext(), "Credentials edited!", Toast.LENGTH_SHORT).show();
}
} else {
Cursor cr2 = db.query(DbConstants.TABLE_NAME, null, DbConstants.APP_ID + "=?" + " AND " + DbConstants.UID_VALUE + "=?", new String[]{activityDbId, myUid}, null, null, null);
if (cr2.moveToNext()) {
db.update(DbConstants.TABLE_NAME, cv, DbConstants.APP_ID + "=?" + " AND " + DbConstants.UID_VALUE + "=?", new String[]{activityDbId, myUid});
Toast.makeText(getApplicationContext(), "Credentials edited!", Toast.LENGTH_SHORT).show();
} else {
db.insert(DbConstants.TABLE_NAME, null, cv);
Log.d("Stored:" + activityDbId, myUid + "->" + myPwd);
mEdit.remove(Constants.NEW_UID);
mEdit.remove(Constants.NEW_PWD);
mEdit.commit();
Toast.makeText(getApplicationContext(), "Credentials stored!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFinishInput() {
super.onFinishInput();
Log.d("onFinishInput", "invoked");
}
#Override
public void onText(CharSequence charSequence) {
}
#Override
public void swipeLeft() {
}
#Override
public void swipeRight() {
}
#Override
public void swipeDown() {
}
#Override
public void swipeUp() {
}
}
2) CustomKeyboardView:
public class CustomKeyboardView extends KeyboardView {
Context mContext;
Boolean caps;
public CustomKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
caps = false;
}
#Override
public boolean setShifted(boolean shifted) {
super.setShifted(shifted);
caps = shifted;
invalidateAllKeys();
return shifted;
}
#Override
public void onDraw(Canvas canvas) {
List<Keyboard.Key> keys = getKeyboard().getKeys();
for (Keyboard.Key key : keys) {
Drawable dr = null;
if (key.codes[0] == Keyboard.KEYCODE_DELETE) {
dr = getResources().getDrawable(R.drawable.keyboard_backspace, mContext.getTheme());
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
} else if (key.codes[0] == Keyboard.KEYCODE_SHIFT) {
dr = getResources().getDrawable(R.drawable.keyboard_shift, mContext.getTheme());
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
} else if (key.codes[0] == 32) { //space bar
int tenDp = Utils.dpToPx(10, mContext);
int twoDp = Utils.dpToPx(2, mContext);
dr = new ColorDrawable(Color.LTGRAY);
dr.setBounds(key.x + twoDp, key.y + (tenDp), key.x + key.width - twoDp, key.y + key.height - (tenDp));
dr.draw(canvas);
}
Paint mPaint = new Paint();
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(Utils.dpToPx(18, mContext));
mPaint.setColor(Color.BLACK);
if (key.label != null) {
String keyLabel = key.label.toString();
if (caps) {
keyLabel = keyLabel.toUpperCase();
}
canvas.drawText(keyLabel, key.x + (key.width / 2),
key.y + (key.height / 2) + Utils.dpToPx(5, mContext), mPaint);
} else if (key.icon != null) {
key.icon.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
key.icon.draw(canvas);
}
}
}
}
3) R.layout.my_custom_keyboard:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/blue">
<ImageView
android:id="#+id/ivRevertKeyboard"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:padding="10dp"
android:scaleType="fitEnd"
android:src="#drawable/keyboard_icon" />
</RelativeLayout>
<com.prasad.CustomKeyboardView
android:id="#+id/keyboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="5dp"
android:keyPreviewHeight="50dp"
android:background="#color/white"
android:keyPreviewLayout="#xml/keyboard_preview"
android:shadowColor="#color/transparent" />
</LinearLayout>
Expected behaviour: The keyboard should be displayed and hidden properly by the system after swapping multiple times with another keyboard.
Please let me know if you need additional details. Any clues will be appreciated.
Regards,
Prasad
how is this?
#Override
public void onClick(View view) {
vibrator.vibrate(Constants.VIBRATE_TIME_MEDIUM);
try {
// imm.hideSoftInputFromInputMethod(token, 0);
// imm.setInputMethod(token, defImeId);
this.switchInputMethod(defImeId);
} catch (Throwable t) { // java.lang.NoSuchMethodError if API_level<11
t.printStackTrace();
}
}

NullpointerException when called alertdialog

I want call alertdialog in my application and getting error
"12-02 09:40:07.500: E/AndroidRuntime(4693): FATAL EXCEPTION: main
12-02 09:40:07.500: E/AndroidRuntime(4693): java.lang.NullPointerException
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.getVolumeControlStream(Activity.java:3714)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Dialog.setOwnerActivity(Dialog.java:188)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.onPrepareDialog(Activity.java:2494)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.onPrepareDialog(Activity.java:2518)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.showDialog(Activity.java:2568)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.showDialog(Activity.java:2527)
12-02 09:40:07.500: E/AndroidRuntime(4693): at com.example.ok1.ToDoCalendarViewMaker$2.onItemLongClick(ToDoCalendarViewMaker.java:170)"
source code:
public class ToDoCalendarViewMaker extends SherlockFragmentActivity implements OnItemLongClickListener {
//final String Tag="States";
public ToDoCalendarViewMaker() {
}
public void makeGrid(Context context, View view, final MyCalendar myCalendar) {
final String Tag="States";
Log.d(Tag, "ljokj до сюдого 4");
GridView myGridView;
final Context myContext;
final Context myContext1;
View myView;
myView = view;
myContext = context;
myGridView = (GridView) myView.findViewById(R.id.gridView);
String[] from = { "text", "background" };
int[] to = { R.id.tvDay, R.id.llDay };
ArrayList<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();
myData = (ArrayList<Map<String, Object>>) myCalendar.myData.clone();
SimpleAdapter sAdapter = new SimpleAdapter(myContext,
myData, R.layout.day_layout, from, to);
Log.d(Tag, "до биндера");
sAdapter.setViewBinder(new MyViewBinder());
Log.d(Tag, "после");
myGridView.setAdapter(sAdapter);
myGridView.setNumColumns(7);
myGridView.setVerticalSpacing(5);
myGridView.setHorizontalSpacing(5);
myGridView.setOnTouchListener(new MyGridOnTouchListener());
myGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id){
Log.d(Tag, "сработал onItemClick= "+ MainActivity.MyFlag_onClick);
if (MainActivity.MyFlag_onClick == true) {
Log.d(Tag, "идем в лист задач ");
//*********работа с БД****************
// создаем объект для данных
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(myContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
//*********работа с БД****************
// Toast.makeText(myContext,
// "" + myCalendar.returnDateById(position) + " + " + id,
// Toast.LENGTH_SHORT).show();
String id_for_listtsk=myCalendar.returnDateById(position).toString();
//добавляем строку в БД
cv.put("data_id", myCalendar.returnDateById(position));
// long rowID = db.insert("mytable", null, cv);
Log.d(Tag, "row inserted, ID = ");
Cursor c = db.query("mytable", null, null, null, null, null, null);
// logCursor(c);
dbHelper.close();
Intent intent = new Intent(myContext, ListTsk.class);
Log.d(Tag, "==== "+id_for_listtsk);
intent.putExtra("dat", id_for_listtsk.toString());
intent.putExtra("currentPagerList", "1");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Context myContext1=myContext.getApplicationContext();
myContext.startActivity(intent);
// return false;
//************************
// ToDoCalendarActivity.this.finish();
}
}
private void logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
if (c!=null) {
if (c.moveToFirst()) {
String str;
do {
str="";
for (String cn: c.getColumnNames()) {
str = str.concat(cn + " = " + c.getString(c.getColumnIndex(cn)) + "; ");
}
Log.d(Tag, str);
} while (c.moveToNext());
}
}
}
});
myGridView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Log.d(Tag, "11111111111111");
String id_for_listtsk=myCalendar.returnDateById(position).toString();
/*
* вызываем диалог
*/
int dialogId = 0;
dialogId = DialogFactory.DIALOG_TASKS;
//ToDoCalendarActivity.showDial(dialogId);//showDialog(dialogId);
showDialog(dialogId);
//***
return true;
}});
//sAdapter.notifyDataSetChanged();
}
#Override
protected Dialog onCreateDialog(int id) {
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(dialogButtonedit1, InputMethodManager.SHOW_IMPLICIT);
return DialogFactory.getDialogById(id, ToDoCalendarActivity.context);//this
}
public static Dialog createCustomAlertTasks(final Context context) {
//Dialog dialog2=null;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from( context );
View layout = inflater.inflate(R.layout.customnew, null);
builder.setView(layout);
Dialog dialog2 = builder.setTitle("Введите новый список")
.create();
return dialog2;
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
return false;
}
}
//********************************************************
class MyViewBinder implements SimpleAdapter.ViewBinder {
int p;
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
int i;
switch (view.getId()) {
// LinearLayout
case R.id.llDay:
i = ((Integer) data).intValue();
if (i == -1)
view.setBackgroundResource(R.drawable.another_day);
else if (i == 0)
view.setBackgroundResource(R.drawable.day);
else if (i == 1)
view.setBackgroundResource(R.drawable.weekend);
else if (i == 2)
p=4;//view.setBackgroundResource(R.drawable.today_another_day);
else if (i == 3)
view.setBackgroundResource(R.drawable.today_day);
else if (i == 4)
p=6;//view.setBackgroundResource(R.drawable.today_weekend);
return true;
}
return false;
}
}
class MyGridOnTouchListener implements OnTouchListener{
final String Tag="States";
#Override
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
Log.d(Tag, "сработал онтач.....");
// TODO Auto-generated method stub
MainActivity.MyFlag_onClick=false;
if (paramMotionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Log.d(Tag, "опустил палец");
ToDoCalendarActivity.touchX1 = paramMotionEvent.getX();
Log.d(Tag, "x1="+String.valueOf(ToDoCalendarActivity.touchX1));
ToDoCalendarActivity.touchY1 = paramMotionEvent.getY();
ToDoCalendarActivity.flag = true;
}
if (paramMotionEvent.getAction() == MotionEvent.ACTION_MOVE) {
ToDoCalendarActivity.touchY2 = paramMotionEvent.getY();
}
if (paramMotionEvent.getAction() == MotionEvent.ACTION_UP) {
ToDoCalendarActivity.touchX2 = paramMotionEvent.getX();
Log.d(Tag, "x2="+String.valueOf(ToDoCalendarActivity.touchX2));
Log.d(Tag, "Поднял палец");
if (ToDoCalendarActivity.flag==true &&
Math.abs(ToDoCalendarActivity.touchX2 - ToDoCalendarActivity.touchX1)>
Math.abs(ToDoCalendarActivity.touchY2 - ToDoCalendarActivity.touchY1)){
if (ToDoCalendarActivity.touchX2>ToDoCalendarActivity.touchX1){
if ((ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1)>50) {
ToDoCalendarActivity.prevMonth();
}
else if (((ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1)<10)) {
MainActivity.MyFlag_onClick=true;
}
Log.d(Tag, String.valueOf(ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1));
ToDoCalendarActivity.flag=false;
} else {
Log.d(Tag, String.valueOf(ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2));
if ((ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2)>50) {
ToDoCalendarActivity.nextMonth();
}
else if (((ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2)<10)) {
MainActivity.MyFlag_onClick=true;
}
ToDoCalendarActivity.flag=false;
}
}
// ToDoCalendarActivity.flag = false;
}
Log.d(Tag, "....................");
if (ToDoCalendarActivity.touchX1==ToDoCalendarActivity.touchX2){
Log.d(Tag, "Значения равны");
MainActivity.MyFlag_onClick=true;
}
return false;
}
}
public static Dialog getDialogById(int id, final Context context) {
Dialog dialog = null;
switch (id) {
case DIALOG_ALERT:
//dialog = createAlertDialog(context);
break;
case DIALOG_PROGRESS:
//dialog = createProgressDialog(context);
break;
case DIALOG_INPUT:
// dialog = Lists.createInputAlert(context);
dialog = Lists.createCustomAlertNew(context);
break;
case DIALOG_CUSTOM:
dialog = Lists.createCustomAlert(context);
break;
case DIALOG_TASKS:
dialog = ToDoCalendarViewMaker.createCustomAlertTasks(context);
break;
}
return dialog;
}
}
public class ToDoCalendarActivity extends Activity implements OnClickListener{
private KillReceiver mKillReceiver;
final String Tag="States";
static private View[] views = new View[3];
private static final String PREF_ACCOUNT_NAME = "accountName";
static MyCalendar[] cArray = new MyCalendar[3];
static ViewFlipper vf;
static int currentView;
View mainView;
AlarmManager alarmManager;
int REQUEST_CODE = 11223344;
static ToDoCalendarViewMaker toDoCalendarViewMaker;
static float touchX1,touchX2,touchY1,touchY2;
static boolean flag;
static int bb = 0;
static Context context;
static TextView myTextView;
static final String SOME_ACTION = "com.BAO.OK1.SOME_ACTION";
TextView[] textViewArray = new TextView[7];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// if (getIntent().getBooleanExtra("finish_cal", true)) {
//
// finish();
// }
// Log.d(Tag, "!!!!!!!!!!!!!!!!!!финализируем календарь"+getIntent().getBooleanExtra("finish_cal", true));
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_layout);
// Log.d(Tag, "ljokj до сюдого");
//кнопки отвечающие за переход по месяцам
Log.d(Tag, "Пытаемся запустить календарь");
View prevButton = findViewById(R.id.prev_button);
prevButton.setOnClickListener(this);
View nextButton = findViewById(R.id.next_button);
nextButton.setOnClickListener(this);
//останавливаем AlarmManager
try {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent_stop_alarm = new Intent(MainActivity.BROADCAST_ACTION);
alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent_stop_alarm, 0));
} catch (Exception e) {
// TODO: handle exception
}
//*******************пытаемся навешать слушатель для закрытия активити
Log.d(Tag, "Пытаемся запустить календарь");
mKillReceiver = new KillReceiver();
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
registerReceiver(mKillReceiver,intentFilter);
Log.d(Tag, "Пытаемся запустить календарь1");
//******************************************************************
vf = (ViewFlipper) findViewById(R.id.flipper);
context = getApplicationContext();
// Log.d(Tag, "ljokj до сюдого 2");
LayoutInflater ltInflater = getLayoutInflater();
for (int i = 0; i<3; i++){
views[i] = ltInflater.inflate(R.layout.grid_layout, null, false);
}
// Log.d(Tag, "ljokj до сюдого 3");
mainView = findViewById(R.id.mainll);
Log.d(Tag, "ljokj до сюдого 3.1");
cArray[0] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю2");
cArray[1] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю3");
cArray[2] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю4");
Resources res = getResources();
MyCalendar.setNamesOfDays(
res.getString(R.string.Mon),
res.getString(R.string.Tue),
res.getString(R.string.Wed),
res.getString(R.string.Thu),
res.getString(R.string.Fri),
res.getString(R.string.Sat),
res.getString(R.string.Sun));
MyCalendar.setNamesOfMonths(
res.getString(R.string.January),
res.getString(R.string.February),
res.getString(R.string.March),
res.getString(R.string.April),
res.getString(R.string.May),
res.getString(R.string.June),
res.getString(R.string.July),
res.getString(R.string.August),
res.getString(R.string.September),
res.getString(R.string.October),
res.getString(R.string.November),
res.getString(R.string.December));
Log.d(Tag, "ljokj до сюдого 4");
cArray[0].setState();
Log.d(Tag, "ljokj до сюдого 4/0");
cArray[1].setState();
cArray[2].setState();
cArray[1].nextMonth();
toDoCalendarViewMaker = new ToDoCalendarViewMaker();
cArray[2].prevMonth();
Log.d(Tag, "ljokj до сюдого 4/1");
toDoCalendarViewMaker.makeGrid(this, views[0], cArray[0]);
Log.d(Tag, "ljokj до сюдого 4/1\1");
toDoCalendarViewMaker.makeGrid(this, views[1], cArray[1]);
Log.d(Tag, "ljokj до сюдого 4/1.2");
toDoCalendarViewMaker.makeGrid(this, views[2], cArray[2]);
Log.d(Tag, "ljokj до сюдого 4/1.3");
Log.d(Tag, "ljokj до сюдого 5");
vf.addView((View) views[0]);
vf.addView((View) views[1]);
vf.addView((View) views[2]);
currentView = 0;
myTextView = (TextView) findViewById(R.id.myText);
textViewArray[0] = (TextView) findViewById(R.id.textData);
textViewArray[1] = (TextView) findViewById(R.id.textView2);
textViewArray[2] = (TextView) findViewById(R.id.textView3);
textViewArray[3] = (TextView) findViewById(R.id.textView4);
textViewArray[4] = (TextView) findViewById(R.id.textView5);
textViewArray[5] = (TextView) findViewById(R.id.textView6);
textViewArray[6] = (TextView) findViewById(R.id.textView7);
// рисуем названия дней недели
Log.d(Tag, "ljokj до сюдого 6");
int j = MyCalendar.beforeFirstDay;
for (int i = 0; i < 7; i++) {
if (j == 7) {
j = 0;
}
textViewArray[i].setText(MyCalendar.namesOfDays[j]);
j++;
}
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
#Override
public void onClick(View v) {
Log.d(Tag, "onClick");
switch (v.getId()) {
case R.id.prev_button:
prevMonth();
break;
case R.id.next_button:
nextMonth();
break;
}
}
//****
public static void nextMonth(){
vf.setInAnimation(AnimationUtils.loadAnimation(context,R.anim.next_appear));
vf.setOutAnimation(AnimationUtils.loadAnimation(context,R.anim.next_disappear));
vf.showNext();
int prevView = currentView - 1;
if (prevView == -1) prevView = 2;
currentView++;
if (currentView == 3) currentView = 0;
cArray[prevView].nextMonth();
cArray[prevView].nextMonth();
cArray[prevView].nextMonth();
toDoCalendarViewMaker.makeGrid(context, views[prevView], cArray[prevView]);
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
public static void prevMonth(){
// Log.d(Tag, "предыдущий месяц");
vf.setInAnimation(AnimationUtils.loadAnimation(context,R.anim.next_appear_1));
vf.setOutAnimation(AnimationUtils.loadAnimation(context,R.anim.next_disappear_1));
vf.showPrevious();
int nextView = currentView + 1;
if (nextView == 3) nextView = 0;
currentView--;
if (currentView == -1) currentView = 2;
cArray[nextView].prevMonth();
cArray[nextView].prevMonth();
cArray[nextView].prevMonth();
toDoCalendarViewMaker.makeGrid(context, views[nextView], cArray[nextView]);
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.d(Tag, "onTouchEvent ToDoCalendarActivity");
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touchX1 = event.getX();
Log.d(Tag, "x1="+String.valueOf(touchX1));
touchY1 = event.getY();
flag = true;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
touchX2 = event.getX();
Log.d(Tag, "x2="+String.valueOf(touchX2));
touchY2 = event.getY();
if (flag==true && Math.abs(touchX2 - touchX1)>Math.abs(touchY2 - touchY1)){
if (touchX2>touchX1) {
Log.d(Tag, String.valueOf(touchX2-touchX1));
prevMonth();flag=false;
} else {
Log.d(Tag, String.valueOf(touchX1-touchX2));
nextMonth();flag=false;
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
flag = false;
}
return super.onTouchEvent(event);
}
//*****
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "Today");
// menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Exit");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
ListTsk.id_for_listtsk=null;
onDestroy();
break;
// case 2:
//
// break;
case 3:
//this.onDestroy();
Intent myintent = new Intent(this, MainActivity.class);
myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myintent.putExtra("finish", true);
startActivity(myintent);
onDestroy();
// break;
}
return super.onOptionsItemSelected(item);
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
try {
//******************************пробуем засунуть сюда настройки
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
String nastrPreferences = settings.getString(PREF_ACCOUNT_NAME, null);
//*******************************
startService(new Intent(this, ServiceUpdate.class).putExtra("preferences", nastrPreferences));
Log.d(Tag, "запустили службу ServiceUpdate");
} catch (Exception e) {
// TODO: handle exception
}
Log.d(Tag, "todocalendarActivity: onDestroy()");
finish();
// db.close();
}
#Override
protected void onStop() {
super.onStop();
Log.d(Tag, "todocalendarActivity: onStop()");
// finish();
}
#Override
protected void onPause() {
super.onPause();
//this.dbHelper.close();
Log.d(Tag, "todocalendarActivity: onPause()");
}
public static void showDial(int num) {
//Toast.makeText(context, "hello", 1000).show();
bb++;
// showDialog(num);
}
#Override
public void onBackPressed() {
// Log.d(Tag, "Была нажата кнопка возврат");
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(100);
return;
}
private final class KillReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
}
may be I have error in raw "return DialogFactory.getDialogById(id, ToDoCalendarActivity.context)" ? May be I must use other context? help me please

Double Tapping on the textView

Eg.,
Welcome to Android World.
Now when I double tap on the space between "Welcome" and "to", the String from "to" to "World" should come in the next line.
That is,
Welcome <\n>
to Android World.
Similarly, when I double tap the space between "to" and "Android", it should be,
Welcome <\n>
to <\n>
Android World.
The first time it works, but the next time it force stops.
I don't know where I am going wrong. Probably it is not getting the onTouchListener properly.
Need Help.
linear_layout = (LinearLayout) findViewById(R.id.linearLayout);
mTextView = new TextView[10];
mTextView[i] = new TextView(this);
mTextView[i].setText("Hello Android Text View");
linear_layout.addView(mTextView[i]);
mTextView[i].setOnTouchListener(this);
mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
#Override
public void onLongPress(MotionEvent e) {
Log.d(TAG, "Long Press event");
Toast.makeText(getBaseContext(), "Long Press", Toast.LENGTH_LONG).show();
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d(TAG, "Double Tap event");
Toast.makeText(getBaseContext(), "Double Tap", Toast.LENGTH_LONG).show();
Log.i("Tag", "------------------------------ " + e.getX() + " " + e.getY());
Layout layout = ((TextView) view).getLayout();
int x = (int)e.getX();
int y = (int)e.getY();
if (layout!=null){
line = layout.getLineForVertical(y);
characterOffset = layout.getOffsetForHorizontal(line, x);
Log.i("index", ""+characterOffset);
}
String text = mTextView[i].getText().toString();
char[] char_txt = text.toCharArray();
int ascii_val = (int)text.charAt(characterOffset);
String rem_txt = "";
//if(ascii_val == 32) {
int n=characterOffset;
while(n < char_txt.length){
rem_txt += char_txt[n];
n++;
}
//}
i++;
String before_tap_txt = text.subSequence(0, characterOffset).toString();
mTextView[i-1].setText(before_tap_txt);
mTextView[i] = new TextView(GestureDetecterExampleActivity.this);
mTextView[i].setText(rem_txt);
linear_layout.addView(mTextView[i]);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
});
mGestureDetector.setIsLongpressEnabled(true);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
view = v;
return mGestureDetector.onTouchEvent(event);
}
Log.d(TAG, "Double Tap event");
/* Toast.makeText(getBaseContext(), "Double Tap",
Toast.LENGTH_LONG).show();*/
Log.i("Tag",
"------------------------------ " + e.getX()
+ " " + e.getY());
Layout layout = ((TextView) view).getLayout();
int x = (int) e.getX();
int y = (int) e.getY();
if (layout != null) {
line = layout.getLineForVertical(y);
characterOffset = layout.getOffsetForHorizontal(
line, x);
Log.i("index", "" + characterOffset);
}
String text = mTextView[i].getText().toString();
char[] char_txt = text.toCharArray();
int ascii_val = (int) text.charAt(characterOffset);
String rem_txt = "";
if(ascii_val == 32) {
int n = characterOffset;
while (n < char_txt.length) {
rem_txt += char_txt[n];
n++;
}
// }
i++;
String before_tap_txt = text.subSequence(0,
characterOffset).toString();
mTextView[i - 1].setText(before_tap_txt.trim());
mTextView[i] = new TextView(
DoubleTapActivity.this);
mTextView[i].setText(rem_txt.trim());
mTextView[i].setOnTouchListener(DoubleTapActivity.this);
linear_layout.addView(mTextView[i]);
return true;
}
else
{
Toast.makeText(DoubleTapActivity.this, "" + text.charAt(characterOffset), Toast
.LENGTH_SHORT).show();
}
return false;
Place this code in ur double tap method.
comment if you need any help.

Categories

Resources