I need to toast something on double tap the screen. I tried the following code. But it's not working. No toast is coming on double tapping. What is wrong with these code?
package a.b.c;
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.widget.Toast;
public class SampleActivity extends Activity implements OnDoubleTapListener,OnGestureListener
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
if(e.getAction()==1)
{
Toast.makeText(getBaseContext(), "onDoubleTap", Toast.LENGTH_LONG).show();
}
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
if(e.getAction()==1)
{
Toast.makeText(getBaseContext(), "onDoubleTapEvent", Toast.LENGTH_LONG).show();
}
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if(e.getAction()==1)
{
Toast.makeText(getBaseContext(), "onSingleTapConfirmed", Toast.LENGTH_LONG).show();
}
return true;
}
I also implemented the OnGestureListener methodes. But have no effect. Please help.
Where do you set the doubletap listener? Try adding this to your oncreate and see if it fixes the issue
GestureDetector detector = new GestureDetector(this, this);
Related
I am using braintree api to get add card in app for payments. It works fines and sometimes crashes randomly,
This is my stacktrace,
E/AndroidRuntime: FATAL EXCEPTION: Thread-833
Process: cl.tempclick, PID: 29509
java.lang.NullPointerException: Attempt to invoke virtual method 'com.braintreepayments.api.internal.HttpClient com.braintreepayments.api.internal.BraintreeHttpClient.setBaseUrl(java.lang.String)' on a null object reference
at com.braintreepayments.api.BraintreeFragment.setConfiguration(BraintreeFragment.java:488)
at com.braintreepayments.api.BraintreeFragment$5.onConfigurationFetched(BraintreeFragment.java:415)
at com.braintreepayments.api.ConfigurationManager.getConfiguration(ConfigurationManager.java:46)
at com.braintreepayments.api.BraintreeFragment.fetchConfiguration(BraintreeFragment.java:412)
at com.braintreepayments.api.BraintreeFragment.waitForConfiguration(BraintreeFragment.java:458)
at com.braintreepayments.api.TokenizationClient.tokenize(TokenizationClient.java:72)
at com.braintreepayments.api.Card.tokenize(Card.java:29)
at cl.tk.ui.activities.sub_activity.AddPayment$UIThreadHandler$1.run(AddPayment.java:364)
at java.lang.Thread.run(Thread.java:818)
This is my Code for the activity,
package cl.tk.ui.activities.sub_activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.braintreepayments.api.BraintreeFragment;
import com.braintreepayments.api.exceptions.InvalidArgumentException;
import com.braintreepayments.api.interfaces.PaymentMethodNonceCreatedListener;
import com.braintreepayments.api.models.CardBuilder;
import com.braintreepayments.api.models.PaymentMethodNonce;
import cl.tk.R;
import cl.tk.controllers.constants.Constants;
import cl.tk.controllers.constants.Enums_String;
import cl.tk.controllers.listeners.ProcessedResult;
import cl.tk.controllers.rest_api.RetrofitAdapters;
import cl.tk.ui.activities.Register;
import cl.tk.ui.fragments.dialog.DTDialog;
import cl.tk.ui.iBAPViews.editext.pattern.PatternedEditText;
import cl.tk.utility.CreditCard;
import cl.tk.utility.CustomException;
import cl.tek.utility.GeneralFunctions;
import cl.tk.utility.MonthYearPicker;
import cl.tk.utility.Validation;
import cl.tk.utility.fonts.FontsManager;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class AddPayment extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener, ProcessedResult,PaymentMethodNonceCreatedListener
{
private Handler uiThreadHandler;
private TextView tvExpiryDate;
//private EditText edCvv,ed_cardHOlderName,edZip;
private PatternedEditText edCardNumber;
private MonthYearPicker myp;
private String mClientToken=null;
private CreditCard creditCard =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_payment);
uiThreadHandler = new UIThreadHandler();
initialze();
downloadBraintreeTOken();
}
private void downloadBraintreeTOken()
{
RetrofitAdapters.get().getBraintreeToken(new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
parseResult(response);
}
#Override
public void failure(RetrofitError error) {
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG);
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = error.getLocalizedMessage();
uiThreadHandler.sendMessage(message);
}
});
}
private void initialze()
{
GeneralFunctions.setToolbarMsgIconHide(this, Constants.ToolbarConstants.PAYMENTS, true);
Button buttonAdd=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_bt_addCard);
buttonAdd.setOnClickListener(this);
GeneralFunctions.setColorSelector(ContextCompat.getColor(this, R.color.color175), ContextCompat.getColor(this, R.color.color1A9), buttonAdd);
TextView tv_defult=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_ct_default);
tv_defult.setOnClickListener(this);
FontsManager.initFormAssets(this, Enums_String.FontsNameLato.SEMIBOLD.toString());
FontsManager.changeFonts(tv_defult);
edCardNumber=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_ed_cardNumber);
tvExpiryDate=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_tv_expiryDate);
tvExpiryDate.setOnTouchListener(this);
myp = new MonthYearPicker(this);
myp.build(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvExpiryDate.setText(myp.getSelectedMonth() + 1 + "/" + myp.getSelectedYear());
}
}, null);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(Enums_String.LocalReceiver.INTERENT.toString());
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.payment_bt_addCard:
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.VALIDATION);
break;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP)
{
if(v.getId()==R.id.payment_tv_expiryDate)
{
if(myp.pickerDialog != null && !myp.pickerDialog.isShowing())
myp.pickerDialog.dismiss();
myp.show();
}
return true;
}
return false;
}
#Override
public <IResponse, IMethod, IExtra> void processedResult(IResponse iResponse, IMethod iMethod, IExtra iExtra) {
}
#Override
public <IResponse, IMethod> void processedResult(IResponse iResponse, IMethod iMethod) {
switch (iMethod.toString())
{
case Constants.CallbackConstants.VIEW_ERROR: {
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SETERROR);
message.obj=iResponse;
uiThreadHandler.sendMessage(message);
}
break;
case Constants.CallbackConstants.BACK:
finish();
break;
}
}
#Override
public void onPaymentMethodNonceCreated(final PaymentMethodNonce paymentMethodNonce) {
}
private void setError(String errorMsg) {
if (errorMsg.equalsIgnoreCase("cardNumber"))
GeneralFunctions.setError(null,String.format(getString(R.string.ed_error_invalid),edCardNumber.getTag().toString()),edCardNumber);
else if (errorMsg.equalsIgnoreCase("cardDate"))
GeneralFunctions.setError(null,String.format(getString(R.string.ed_error_invalid),tvExpiryDate.getTag().toString()),tvExpiryDate);
}
private class UIThreadHandler extends Handler {
#Override
public void handleMessage(Message msg)
{
switch (msg.what) {
case Constants.ActivityBasicsCode.CARDERROR:
GeneralFunctions.setError((CustomException)msg.obj,null,null);
break;
case Constants.ActivityBasicsCode.SETERROR:
setError(msg.obj.toString());
break;
case Constants.ActivityBasicsCode.SHOWTOAST:
{
String text=(String)msg.obj;
GeneralFunctions.showToast(text,AddPayment.this);
}
break;
case Constants.ActivityBasicsCode.HIDEDIALOG:
GeneralFunctions.hideProgressDialog(Constants.DialogConstants.Transparent, AddPayment.this);
break;
case Constants.ActivityBasicsCode.SHOWDIALOG:
{
DTDialog dtDialog=DTDialog.newInstance();
GeneralFunctions.showProgressDialog(dtDialog, Constants.DialogConstants.Transparent, AddPayment.this);
}break;
case Constants.ActivityBasicsCode.VALIDATION: {
new Thread(new Runnable() {
#Override
public void run()
{
try {
if(Validation.validate(AddPayment.this)) {
creditCard = new CreditCard(GeneralFunctions.getText(edCardNumber),GeneralFunctions.getText(tvExpiryDate),AddPayment.this);
boolean validation = creditCard.validateCard();
if (validation) {
if(mClientToken==null) {
downloadBraintreeTOken();
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = getString(R.string.toast_payment_token);
uiThreadHandler.sendMessage(message);
return;
}
BraintreeFragment braintreeFragment= BraintreeFragment.newInstance(AddPayment.this, mClientToken);
if(null==braintreeFragment)
{
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = getString(R.string.toast_payment_fragment);
uiThreadHandler.sendMessage(message);
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.SHOWDIALOG);
}
else {
CardBuilder cardBuilder = new CardBuilder()
.cardNumber(creditCard.getNumber().replaceAll("-", "").trim())
.expirationDate(creditCard.getExpriyDate());
com.braintreepayments.api.Card.tokenize(braintreeFragment, cardBuilder); //On this line my app crashes randomly
}
}
}
}catch (CustomException e)
{
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.CARDERROR);
message.obj=e;
uiThreadHandler.sendMessage(message);
} catch (InvalidArgumentException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
super.handleMessage(msg);
}
}
}
This is my gradle version,
compile 'com.braintreepayments.api:braintree:2.+'
Full disclosure: I work for Braintree.
Are you refreshing the client token every time you go through the checkout process as required? I see that you are only downloading the Braintree token from the server if it is null.
Without having any insight into your CreditCard class or its validateCard method, another possibility may be that the CardBuilder object you are passing into Card.tokenize may not be well-formed.
If you are still having trouble, please reach out to Braintree support for help debugging your integration.
I have a viewpager and several fragments.I extend a ViewPager and implement a my own class.Also i implemented onInterceptTouchEvent method.Now when i swipe it doesn't work.I think onInterceptTouchEvent intercept them. How to handle this?
package com.android.ho;
import com.sph.custom.ViewPagerWithTapGestreDetection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
static final int ITEMS = 20;
MyAdapter mAdapter;
//ViewPager mPager;
ViewPagerWithTapGestreDetection mPager;
//ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
mPager.setId(5000);
mPager.setImageOnTapCallback(this);
mPager.setAdapter(mAdapter);
//mPager.setOffscreenPageLimit(1);
mPager.setOnPageChangeListener(this);
/*
Button button = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
*/
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return MyFragment.newInstance("1.pdf");
case 1: // Fragment # 1 - This will show image
return MyFragment.newInstance("2.pdf");
case 2: // Fragment # 1 - This will show image
return MyFragment.newInstance("3.pdf");
case 3: // Fragment # 1 - This will show image
return MyFragment.newInstance("4.pdf");
case 4: // Fragment # 1 - This will show image
return MyFragment.newInstance("5.pdf");
default:// Fragment # 2-9 - Will show list
return MyFragment.newInstance("1.pdf");
}
}
}
#Override
public void tapDetected() {
// TODO Auto-generated method stub
Log.e("tapDetected", "tapDetected");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
Log.e("onPageScrolled", "onPageScrolled");
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageSelected", "onPageSelected");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "onDestroy onDestroy onDestroy");
}
}
This is my fragment class
package com.android.ho;
import java.io.File;
import java.io.InputStream;
import com.epapyrus.plugpdf.core.viewer.ReaderView;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyFragment extends Fragment{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static int count = 1;
static String file;
TextView txt;
ReaderView readerView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
file = message;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
try {
File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
readerView = (ReaderView) v.findViewById(R.id.pdfviews);
//readerView.setOnClickListener(this);
Log.e("readerView", fl.toString());
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return true;
}
});
// readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
if (count > 5)
count = 1;
readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
Log.e("Inside onCreateView count is ", "" + count);
count++;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
/*v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Log.d("PDFVIEW", "onDestroyView");
try {
if (readerView != null) {
readerView.clear();
// readerView.clearAllField(5);
// readerView.destroyDrawingCache();
// readerView.
// readerView=null;
// mPDFView.purgeMemory();
// mPDFView.destroy();//added to force release memory
// mPDFView = null;
}
Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my custom viewpager class
package com.android.ho
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import com.sph.bh.ImageOnTapCallback;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;
public class ViewPagerWithTapGestreDetection extends ViewPager {
private ImageOnTapCallback imageOnTapCallback;
private GestureDetector tapGestureDetector;
private OnGestureListener mGestureListener;
public ViewPagerWithTapGestreDetection(Context context) {
super(context);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
super(context, attrs);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Don't let any touches be passed down to the children automatically
Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("onTouchEvent", "onTouchEvent");
if (imageOnTapCallback != null) {
tapGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
public ImageOnTapCallback getImageOnTapCallback() {
return imageOnTapCallback;
}
public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
this.imageOnTapCallback = imageOnTapCallback;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");
if (null != imageOnTapCallback) {
imageOnTapCallback.tapDetected();
}
return super.onSingleTapConfirmed(e);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap", "onDoubleTap");
return super.onDoubleTap(e);
}
#Override
public void onLongPress(MotionEvent e) {
Log.d("onLongPress", "onLongPress");
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d("onScroll", "onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e("onFling ", "onFling");
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
I think onInterceptTouchEvent intercept them.
Well, you are returning true from onInterceptTouchEvent(), which means, that as a ViewGroup you do not want any touch event to be passed to children, instead pass that touch event to onTouchEvent().
You should listen for event in onInterceptTouchEvent() return false until you see that this is such a gesture, that shouldn't be handled by children. And on that point only you should return true.
I have a viewpager with several fragments in the viewpager.I need to handle click event.I have already implement the onTouch event,but its not trigger for click event.When i swiping onTouch is triggering.I don't know why it's not trigger for click event.
This is my viewpager class
package com.android.ho;
import com.sph.custom.ViewPagerWithTapGestreDetection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
static final int ITEMS = 20;
MyAdapter mAdapter;
//ViewPager mPager;
ViewPagerWithTapGestreDetection mPager;
//ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
mPager.setId(5000);
mPager.setImageOnTapCallback(this);
mPager.setAdapter(mAdapter);
//mPager.setOffscreenPageLimit(1);
mPager.setOnPageChangeListener(this);
/*
Button button = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
*/
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return MyFragment.newInstance("1.pdf");
case 1: // Fragment # 1 - This will show image
return MyFragment.newInstance("2.pdf");
case 2: // Fragment # 1 - This will show image
return MyFragment.newInstance("3.pdf");
case 3: // Fragment # 1 - This will show image
return MyFragment.newInstance("4.pdf");
case 4: // Fragment # 1 - This will show image
return MyFragment.newInstance("5.pdf");
default:// Fragment # 2-9 - Will show list
return MyFragment.newInstance("1.pdf");
}
}
}
#Override
public void tapDetected() {
// TODO Auto-generated method stub
Log.e("tapDetected", "tapDetected");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
Log.e("onPageScrolled", "onPageScrolled");
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageSelected", "onPageSelected");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "onDestroy onDestroy onDestroy");
}
}
This is my fragment class
package com.android.ho;
import java.io.File;
import java.io.InputStream;
import com.epapyrus.plugpdf.core.viewer.ReaderView;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyFragment extends Fragment{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static int count = 1;
static String file;
TextView txt;
ReaderView readerView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
file = message;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
try {
File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
readerView = (ReaderView) v.findViewById(R.id.pdfviews);
//readerView.setOnClickListener(this);
Log.e("readerView", fl.toString());
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return true;
}
});
// readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
if (count > 5)
count = 1;
readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
Log.e("Inside onCreateView count is ", "" + count);
count++;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
/*v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Log.d("PDFVIEW", "onDestroyView");
try {
if (readerView != null) {
readerView.clear();
// readerView.clearAllField(5);
// readerView.destroyDrawingCache();
// readerView.
// readerView=null;
// mPDFView.purgeMemory();
// mPDFView.destroy();//added to force release memory
// mPDFView = null;
}
Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my custom viewpager class
package com.android.ho
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import com.sph.bh.ImageOnTapCallback;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;
public class ViewPagerWithTapGestreDetection extends ViewPager {
private ImageOnTapCallback imageOnTapCallback;
private GestureDetector tapGestureDetector;
private OnGestureListener mGestureListener;
public ViewPagerWithTapGestreDetection(Context context) {
super(context);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
super(context, attrs);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Don't let any touches be passed down to the children automatically
Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("onTouchEvent", "onTouchEvent");
if (imageOnTapCallback != null) {
tapGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
public ImageOnTapCallback getImageOnTapCallback() {
return imageOnTapCallback;
}
public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
this.imageOnTapCallback = imageOnTapCallback;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");
if (null != imageOnTapCallback) {
imageOnTapCallback.tapDetected();
}
return super.onSingleTapConfirmed(e);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap", "onDoubleTap");
return super.onDoubleTap(e);
}
#Override
public void onLongPress(MotionEvent e) {
Log.d("onLongPress", "onLongPress");
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d("onScroll", "onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e("onFling ", "onFling");
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
Now when i click it identified by the onInterceptTouchEvent in the ViewPagerWithTapGestreDetection class.So i need to view a Horizontal scrollbar when i click.Is it the correct way to call it inside onInterceptTouchEvent ?
How do I use double tap events in an activity? The double tap event or long click method working (though the method is getting overriden) I've just put in a toast message in each of these methods and yet no result! Can you help?
The easiest way to do a double-tap is to detect it with a GestureDetector. The "trick" is to be sure you delegate the Activity's onTouchEvent to the GestureDetector's onTouchEvent:
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;
public class MainActivity extends Activity {
private GestureDetector gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onDoubleTap(MotionEvent e) {
Toast.makeText(MainActivity.this, "double tap", Toast.LENGTH_SHORT).show();
return true;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
return super.onTouchEvent(event);
}
}
I'm trying to start a very simple jWebSocket Client on Android and connect it to my local server. I'm using the JWC class from the demo together with jWebSocket 1.0 beta 8 and Android 4.0.3, my code looks like this:
import org.jwebsocket.api.WebSocketClientEvent;
import org.jwebsocket.api.WebSocketClientTokenListener;
import org.jwebsocket.api.WebSocketPacket;
import org.jwebsocket.client.token.BaseTokenClient;
import org.jwebsocket.kit.WebSocketException;
import org.jwebsocket.token.Token;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import cased.smids.communication.JWC;
public class TasksActivity extends Activity implements WebSocketClientTokenListener {
Spinner spinner;
Button btn_Start;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
JWC.init();
spinner = (Spinner)findViewById(R.id.sp_Task);
btn_Start = (Button)findViewById(R.id.btn_Start);
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(
this,
R.array.Tasks,
android.R.layout.simple_spinner_item
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn_Start.setOnClickListener(new View.OnClickListener() {
public void onClick(View src) {
switch (src.getId()) {
case R.id.btn_Start:
if (spinner.getSelectedItem().toString().equals("Connect")) {
try {
System.out.println("connecting manually...");
JWC.open();
} catch (WebSocketException e) {
e.printStackTrace();
}
}
default:
break;
}
}
});
}
#Override
protected void onResume() {
super.onResume();
System.out.println("* opening... ");
try {
JWC.addListener(this);
JWC.open();
} catch (WebSocketException ex) {
System.out.println("* exception: " + ex.getMessage());
}
}
#Override
protected void onPause() {
System.out.println("* closing... ");
try {
JWC.close();
JWC.removeListener(this);
} catch (WebSocketException ex) {
System.out.println("* exception: " + ex.getMessage());
}
super.onPause();
}
public void processClosed(WebSocketClientEvent arg0) {
System.out.println("closed");
}
public void processOpened(WebSocketClientEvent arg0) {
System.out.println("opened");
}
public void processOpening(WebSocketClientEvent arg0) {
System.out.println("opening");
}
public void processPacket(WebSocketClientEvent arg0, WebSocketPacket arg1) {
System.out.println("packet");
}
public void processReconnecting(WebSocketClientEvent arg0) {
System.out.println("reconnecting");
}
public void processToken(WebSocketClientEvent arg0, Token arg1) {
System.out.println("token");
}
}
so basically it's just a spinner and a button. For now, all I want to do is connect to my local jWebSocketServer. The demo-app (the .apk package from the website, if I import the code eclipse tells me to remove many "#Overwrite" before it compiles the code - after that same "bug" occurs) works with my server so it has to be the code. Right now all I get is "connecting..." and about 0.1s later "closed". Every time.
btw. the app has the right INTERNET and ACCESS_NETWORK_STATE so that shouldn't be a problem.
i will be grateful for any help.
Cheers
Turns out, BaseTokenClient.open() is catching all exceptions and doing nothing about it (silent fail). In my case - NetworkOnMainThreadException. Mystery solved.