Creating a two state button in Android - android

I'm trying to understand how to make a button that latches onto a value when it is pressed, when it's pressed again it unlatches.
My method for this is as follows:
boolean r1 = false;
boolean r2 = true;
private boolean flipFlop(boolean read, int i)
{
if(read == true)
{
if (r1 == true && r2 == false)
{
r1 = false;
r2 = true;
}
else if(r1 == false && r2 == true)
{
r1 = true;
r2 = false;
}
}
return r1;
}
flipFlop method is called under onTouch, like so:
public boolean onTouch(View view, MotionEvent motion)
{
boolean pressCheck = false;
switch(motion.getAction())
{
case MotionEvent.ACTION_UP:
{
pressCheck = flipFlop(view.isPressed(), 1);
textView.setText("State is: " + pressCheck);
}
case MotionEvent.ACTION_DOWN:
{
pressCheck = flipFlop(view.isPressed(), 1);
textView.setText("State is: " + pressCheck);
}
}
return false;
}
When clicking once, the state is set to false and doesn't change.
When double-clicking, it flipflops between the two states. Why is that?
Also, when I tried making it with an array to hold the states, it latched to true and Doesn't change when double-tapping:
private boolean[][] latch = {{false, false, false}, {true, true, true}};
public boolean flipFlop(boolean read, int i)
{
if(read == true)
{
if(latch[i][2] == true && latch[i][1] == false)
{
latch[i][1] = true;
latch[i][2] = false;
}
else if(latch[i][2] == false && latch[i][1] == true)
{
latch[i][1] = false;
latch[i][2] = true;
}
}
return latch[i][1];
}

Related

booleans default to false when getting value from a different class

when i try to get a true/false value from a different class it seems that it is defaulting to false. here are the snippets of my code that should be the problem. the first snippet is the class i'm getting the values from, the second one is the one that is requesting that information. and at the bottom of the second class is the function that should make the class render on the apps screen but seems to not work at all every time. you should be able to understand my coding cause i practice the art of commenting profusely.
private boolean AddProb;
private boolean SubProb;
private boolean MultiProb;
private boolean DivisProb;
public int ANum = 0;
public int SNum;
public int MNum;
public int DNum;
//ProblemSelector PS = new ProblemSelector();
CheckBox checkbox1, checkbox2, checkbox3, checkbox4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_problem_selector);
checkbox1 = (CheckBox) findViewById(R.id.checkBox1);
checkbox2 = (CheckBox) findViewById(R.id.checkBox2);
checkbox3 = (CheckBox) findViewById(R.id.checkBox3);
checkbox4 = (CheckBox) findViewById(R.id.checkBox4);
/** waits for checkbox1 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
checkbox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
AddProb = true;
Toast.makeText(getBaseContext(), "Addition: True", Toast.LENGTH_SHORT).show();
System.out.println("Addition: True");
if(AddProb) {
Log.d("ProblemSelector.java","AddProb did successfully change to true");
} else if(!AddProb){
Log.d("ProblemSelector.java","AddProb did not successfully change to true");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 50-56");
}
} else {
AddProb = false;
Toast.makeText(getBaseContext(), "Addition: False", Toast.LENGTH_SHORT).show();
System.out.println("Addition: False");
if(AddProb) {
Log.d("ProblemSelector.java","AddProb did successfully change to false");
} else if(!AddProb) {
Log.d("ProblemSelector.java","AddProb did not successfully change to false");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 61-67");
}
}
}
});
/** waits for checkbox2 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
SubProb = true;
Toast.makeText(getBaseContext(), "Subtraction: True", Toast.LENGTH_SHORT).show();
System.out.println("Subtraction: True");
if(SubProb) {
Log.d("ProblemSelector.java","SubProb did successfully change to true");
} else if(!SubProb) {
Log.d("ProblemSelector.java","SubProb did not successfully change to true");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 82-88");
}
if(AddProb == false) {
SNum = 0;
}
else if(AddProb == true) {
SNum = 1;
}
} else {
SubProb = false;
Toast.makeText(getBaseContext(), "Subtraction: False", Toast.LENGTH_SHORT).show();
System.out.println("Subtraction: False");
if(SubProb) {
Log.d("ProblemSelector.java","SubProb did successfully change to false");
} else if(!SubProb) {
Log.d("ProblemSelector.java","SubProb did not successfully change to false");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 99-105");
}
}
}
});
/** waits for checkbox3 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
checkbox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
MultiProb = true;
Toast.makeText(getBaseContext(), "Multiplication: True", Toast.LENGTH_SHORT).show();
System.out.println("Multiplication: True");
if(MultiProb) {
Log.d("ProblemSelector.java","MultiProb did successfully change to true");
} else if(!MultiProb) {
Log.d("ProblemSelector.java","MultiProb did not successfully change to true");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 120-126");
}
if(AddProb == false && SubProb == false) {
MNum = 0;
}
else if(AddProb == true && SubProb == false || AddProb == false && SubProb == true) {
MNum = 1;
}
else if(AddProb == true && SubProb == true) {
MNum = 2;
}
} else {
MultiProb = false;
Toast.makeText(getBaseContext(), "Multiplication: False", Toast.LENGTH_SHORT).show();
System.out.println("Multiplication: False");
if(MultiProb) {
Log.d("ProblemSelector.java","MultiProb did successfully change to false");
} else if(!MultiProb) {
Log.d("ProblemSelector.java","MultiProb did not successfully change to false");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 140-146");
}
}
}
});
/** waits for checkbox4 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
/** and determines if the value of the boolean for this function has changed successfully or not **/
checkbox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
DivisProb = true;
Toast.makeText(getBaseContext(), "Division: True", Toast.LENGTH_SHORT).show();
System.out.println("Division: True");
if(DivisProb) {
Log.d("ProblemSelector.java","DivisProb did successfully change to true");
} else if(!DivisProb) {
Log.d("ProblemSelector.java","DivisProb did not successfully change to true");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 162-168");
}
if(AddProb == false && SubProb == false && MultiProb == false) {
DNum = 0;
}
else if(AddProb == true && SubProb == false && MultiProb == false || AddProb == false && SubProb == true && MultiProb == false || AddProb == false && SubProb == false && MultiProb == true) {
DNum = 1;
}
else if(AddProb == true && SubProb == true && MultiProb == false || AddProb == false && SubProb == true && MultiProb == true || AddProb == true && SubProb == false && MultiProb == true) {
DNum = 2;
}
else if(AddProb == true && SubProb == true && MultiProb == true) {
DNum = 3;
}
} else {
DivisProb = false;
Toast.makeText(getBaseContext(), "Division: False", Toast.LENGTH_SHORT).show();
System.out.println("Division: False");
if(DivisProb) {
Log.d("ProblemSelector.java","DivisProb did successfully change to false");
} else if(!DivisProb) {
Log.d("ProblemSelector.java","DivisProb did not successfully change to false");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 184-189");
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_problem_selector, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** this is called when the user hits the continue button **/
public void DifficultyMenu(View view) {
String S1 = String.valueOf(AddProb);
Log.d("ProblemSelector.java","AddProb: " + S1);
Intent DifficultyView = new Intent(this, DifficultyMenu.class);
//DifficultyView.putExtra("addProb", PS.AddProb);
//DifficultyView.putExtra("subProb", PS.SubProb);
//DifficultyView.putExtra("multiProb", PS.MultiProb);
//DifficultyView.putExtra("divisProb", PS.DivisProb);
startActivity(DifficultyView);
}
/** this converts the 1st version bools to 2nd version bools and outputs the values to the command line **/
public boolean AddP = AddProb;
public boolean SubP = SubProb;
public boolean MultiP = MultiProb;
public boolean DivisP = DivisProb;
}
here is the second class.
private boolean AddP = PS.AddP;
private boolean SubP = PS.SubP;
private boolean MultiP = PS.MultiP;
private boolean DivisP = PS.DivisP;
private int ANum = PS.ANum;
private int SNum = PS.SNum;
private int MNum = PS.MNum;
private int DNum = PS.DNum;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_difficulty_menu);
// here you'll retrieve the data sent...you can google how to do that.
// get the list view
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// List view Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// List view Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// List view Group collapsed listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// List view on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition), Toast.LENGTH_SHORT)
.show();
/** converts the selected number in the expandable list to a usable integer variable **/
/** also detects if a Difficulty has been selected for each for of problem to practice **/
/** also gives an error to debug console level if something unexpected has happened **/
if(listDataHeader.get(groupPosition).equals("AdditionDifficulty")) {
String St1 = listDataHeader.get(childPosition);
int AddDiff = Integer.parseInt(St1);
if(PS.AddP) {
AChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 123 : for some reason this seems to have happened");
}
}
else if(listDataHeader.get(groupPosition).equals("SubtractionDifficulty")) {
String St2 = listDataHeader.get(childPosition);
int SubDiff = Integer.parseInt(St2);
if(PS.SubP) {
SChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 132 : for some reason this seems to have happened");
}
}
else if(listDataHeader.get(groupPosition).equals("MultiplicationDifficulty")) {
String St3 = listDataHeader.get(childPosition);
int MultiDIff = Integer.parseInt(St3);
if(PS.MultiP) {
MChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 141 : for some reason this seems to have happened");
}
}
else if(listDataHeader.get(groupPosition).equals("DivisionDifficulty")) {
String St4 = listDataHeader.get(childPosition);
int DivisDiff = Integer.parseInt(St4);
if(PS.DivisP) {
DChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 150 : for some reason this seems to have happened");
}
}
else {
Log.e("DifficultyMenu.java","could not parse a group position when user selected a field");
}
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
// Adding child data
if(AddP) { listDataHeader.add("AdditionDifficulty"); }
if(SubP) { listDataHeader.add("SubtractionDifficulty"); }
if(MultiP) { listDataHeader.add("MultiplicationDifficulty"); }
if(DivisP) { listDataHeader.add("DivisionDifficulty"); }
System.out.println(listDataHeader);
/** this removes fields that the user has not selected to practice **/
// if(!PS.AddProb) { listDataHeader.remove("AdditionDifficulty"); }
// if(!PS.SubProb) { listDataHeader.remove("SubtractionDifficulty"); }
// if(!PS.MultiProb) { listDataHeader.remove("MultiplicationDifficulty"); }
// if(!PS.DivisProb) { listDataHeader.remove("DivisionDifficulty"); }
// Adding child data
List<String> AdditionDifficulty = new ArrayList<>();
while (true) {
if (T1 < 11) {
String S1 = Integer.toString(T1);
AdditionDifficulty.add(S1);
T1++;
} else {
break;
}
}
List<String> SubtractionDifficulty = new ArrayList<>();
while (true) {
if (T2 < 11) {
String S2 = Integer.toString(T2);
SubtractionDifficulty.add(S2);
T2++;
} else {
break;
}
}
List<String> MultiplicationDifficulty = new ArrayList<>();
while (true) {
if (T3 < 11) {
String S3 = Integer.toString(T3);
MultiplicationDifficulty.add(S3);
T3++;
} else {
break;
}
}
List<String> DivisionDifficulty = new ArrayList<>();
while (true) {
if (T4 < 11) {
String S4 = Integer.toString(T4);
DivisionDifficulty.add(S4);
T4++;
} else {
break;
}
}
/** this draws out the Expandable lists **/
if(AddP) {
listDataChild.put(listDataHeader.get(ANum), AdditionDifficulty);
} else {
Log.d("DifficultyMenu.java","Something went wrong at line: 230");
}
if(SubP) {
listDataChild.put(listDataHeader.get(SNum), SubtractionDifficulty);
} else {
Log.d("DifficultyMenu.java","Something went wrong at line: 231");
}
if(MultiP) {
listDataChild.put(listDataHeader.get(MNum), MultiplicationDifficulty);
} else {Log.d("DifficultyMenu.java","Something went wrong at line: 232");
}
if(DivisP) {
listDataChild.put(listDataHeader.get(DNum), DivisionDifficulty);
} else {Log.d("DifficultyMenu.java","Something went wrong at line: 233");
}
}

Does vuforia support Andengine?

public class Demo extends LayoutGameActivity implements SampleApplicationControl,SampleAppMenuInterface {
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final float AUTOWRAP_WIDTH = 720 - 50 - 50;
private EditText mEditText;
private Font mFont;
private Text mText;
private Line mRight;
private Line mLeft;
private static final String LOGTAG = "ImageTargets";
SampleApplicationSession vuforiaAppSession;
private DataSet mCurrentDataset;
private int mCurrentDatasetSelectionIndex = 0;
private int mStartDatasetsIndex = 0;
private int mDatasetsNumber = 0;
private ArrayList<String> mDatasetStrings = new ArrayList<String>();
// Our OpenGL view:
private SampleApplicationGLView mGlView;
// Our renderer:
private ImageTargetRenderer mRenderer;
private GestureDetector mGestureDetector;
// The textures we will use for rendering:
private Vector<Texture> mTextures;
private boolean mSwitchDatasetAsap = false;
private boolean mFlash = false;
private boolean mContAutofocus = false;
private boolean mExtendedTracking = false;
private View mFlashOptionView;
private RelativeLayout mUILayout;
private SampleAppMenu mSampleAppMenu;
LoadingDialogHandler loadingDialogHandler = new LoadingDialogHandler(this);
// Alert Dialog used to display SDK errors
private AlertDialog mErrorDialog;
boolean mIsDroidDevice = false;
// Called when the activity first starts or the user navigates back to an
// activity.
// Process Single Tap event to trigger autofocus
private class GestureListener extends
GestureDetector.SimpleOnGestureListener
{
// Used to set autofocus one second after a manual focus is triggered
private final Handler autofocusHandler = new Handler();
#Override
public boolean onDown(MotionEvent e)
{
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e)
{
// Generates a Handler to trigger autofocus
// after 1 second
autofocusHandler.postDelayed(new Runnable()
{
public void run()
{
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_TRIGGERAUTO);
if (!result)
Log.e("SingleTapUp", "Unable to trigger focus");
}
}, 1000L);
return true;
}
}
// We want to load specific textures from the APK, which we will later use
// for rendering.
private void loadTextures()
{
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBrass.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBlue.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotRed.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("ImageTargets/Buildings.jpeg",
getAssets()));
}
// Called when the activity will start interacting with the user.
#Override
protected void onResume()
{
Log.d(LOGTAG, "onResume");
super.onResume();
vuforiaAppSession = new SampleApplicationSession(this);
startLoadingAnimation();
mDatasetStrings.add("StonesAndChips.xml");
mDatasetStrings.add("Tarmac.xml");
// mDatasetStrings.add("my_first.xml");
vuforiaAppSession
.initAR(this, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mGestureDetector = new GestureDetector(this, new GestureListener());
// Load any sample specific textures:
mTextures = new Vector<Texture>();
loadTextures();
mIsDroidDevice = android.os.Build.MODEL.toLowerCase().startsWith(
"droid");
// This is needed for some Droid devices to force portrait
if (mIsDroidDevice)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
try
{
vuforiaAppSession.resumeAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Resume the GL view:
if (mGlView != null)
{
mGlView.setVisibility(View.VISIBLE);
mGlView.onResume();
}
}
// Callback for configuration changes the activity handles itself
#Override
public void onConfigurationChanged(Configuration config)
{
Log.d(LOGTAG, "onConfigurationChanged");
super.onConfigurationChanged(config);
vuforiaAppSession.onConfigurationChanged();
}
// Called when the system is about to start resuming a previous activity.
#Override
protected void onPause()
{
Log.d(LOGTAG, "onPause");
super.onPause();
if (mGlView != null)
{
mGlView.setVisibility(View.INVISIBLE);
mGlView.onPause();
}
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
try
{
vuforiaAppSession.pauseAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
}
// The final call you receive before your activity is destroyed.
#Override
protected void onDestroy()
{
Log.d(LOGTAG, "onDestroy");
super.onDestroy();
try
{
vuforiaAppSession.stopAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Unload texture:
mTextures.clear();
mTextures = null;
System.gc();
}
// Initializes AR application components.
private void initApplicationAR()
{
// Create OpenGL ES view:
int depthSize = 16;
int stencilSize = 0;
boolean translucent = Vuforia.requiresAlpha();
mGlView = new SampleApplicationGLView(this);
mGlView.init(translucent, depthSize, stencilSize);
mRenderer = new ImageTargetRenderer(this, vuforiaAppSession);
mRenderer.setTextures(mTextures);
mGlView.setRenderer(mRenderer);
}
private void startLoadingAnimation()
{
LayoutInflater inflater = LayoutInflater.from(this);
mUILayout = (RelativeLayout) inflater.inflate(R.layout.camera_overlay,
null, false);
mUILayout.setVisibility(View.VISIBLE);
mUILayout.setBackgroundColor(Color.BLACK);
// Gets a reference to the loading dialog
loadingDialogHandler.mLoadingDialogContainer = mUILayout
.findViewById(R.id.loading_indicator);
// Shows the loading indicator at start
loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.SHOW_LOADING_DIALOG);
// Adds the inflated layout to the view
addContentView(mUILayout, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
// Methods to load and destroy tracking data.
#Override
public boolean doLoadTrackersData()
{
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset == null)
mCurrentDataset = objectTracker.createDataSet();
if (mCurrentDataset == null)
return false;
if (!mCurrentDataset.load(
mDatasetStrings.get(mCurrentDatasetSelectionIndex),
STORAGE_TYPE.STORAGE_APPRESOURCE))
return false;
if (!objectTracker.activateDataSet(mCurrentDataset))
return false;
int numTrackables = mCurrentDataset.getNumTrackables();
for (int count = 0; count < numTrackables; count++)
{
Trackable trackable = mCurrentDataset.getTrackable(count);
if(isExtendedTrackingActive())
{
trackable.startExtendedTracking();
}
String name = "Current Dataset : " + trackable.getName();
trackable.setUserData(name);
Log.d(LOGTAG, "UserData:Set the following user data "
+ (String) trackable.getUserData());
}
return true;
}
#Override
public boolean doUnloadTrackersData()
{
// Indicate if the trackers were unloaded correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset != null && mCurrentDataset.isActive())
{
if (objectTracker.getActiveDataSet().equals(mCurrentDataset)
&& !objectTracker.deactivateDataSet(mCurrentDataset))
{
result = false;
} else if (!objectTracker.destroyDataSet(mCurrentDataset))
{
result = false;
}
mCurrentDataset = null;
}
return result;
}
#Override
public void onInitARDone(SampleApplicationException exception)
{
if (exception == null)
{
initApplicationAR();
mRenderer.mIsActive = true;
// Now add the GL surface view. It is important
// that the OpenGL ES surface view gets added
// BEFORE the camera is started and video
// background is configured.
addContentView(mGlView, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// Sets the UILayout to be drawn in front of the camera
mUILayout.bringToFront();
// Sets the layout background to transparent
mUILayout.setBackgroundColor(Color.TRANSPARENT);
try
{
vuforiaAppSession.startAR(CameraDevice.CAMERA.CAMERA_DEFAULT);
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
mContAutofocus = true;
else
Log.e(LOGTAG, "Unable to enable continuous autofocus");
mSampleAppMenu = new SampleAppMenu(this, this, "Image Targets",
mGlView, mUILayout, null);
setSampleAppMenuSettings();
} else
{
Log.e(LOGTAG, exception.getString());
showInitializationErrorMessage(exception.getString());
}
}
// Shows initialization error messages as System dialogs
public void showInitializationErrorMessage(String message)
{
final String errorMessage = message;
runOnUiThread(new Runnable()
{
public void run()
{
if (mErrorDialog != null)
{
mErrorDialog.dismiss();
}
// Generates an Alert Dialog to show the error message
AlertDialog.Builder builder = new AlertDialog.Builder(
Demo.this);
builder
.setMessage(errorMessage)
.setTitle(getString(R.string.INIT_ERROR))
.setCancelable(false)
.setIcon(0)
.setPositiveButton(getString(R.string.button_OK),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
finish();
}
});
mErrorDialog = builder.create();
mErrorDialog.show();
}
});
}
#Override
public void onQCARUpdate(State state)
{
if (mSwitchDatasetAsap)
{
mSwitchDatasetAsap = false;
TrackerManager tm = TrackerManager.getInstance();
ObjectTracker ot = (ObjectTracker) tm.getTracker(ObjectTracker
.getClassType());
if (ot == null || mCurrentDataset == null
|| ot.getActiveDataSet() == null)
{
Log.d(LOGTAG, "Failed to swap datasets");
return;
}
doUnloadTrackersData();
doLoadTrackersData();
}
}
#Override
public boolean doInitTrackers()
{
// Indicate if the trackers were initialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
Tracker tracker;
// Trying to initialize the image tracker
tracker = tManager.initTracker(ObjectTracker.getClassType());
if (tracker == null)
{
Log.e(
LOGTAG,
"Tracker not initialized. Tracker already initialized or the camera is already started");
result = false;
} else
{
Log.i(LOGTAG, "Tracker successfully initialized");
}
return result;
}
#Override
public boolean doStartTrackers()
{
// Indicate if the trackers were started correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.start();
return result;
}
#Override
public boolean doStopTrackers()
{
// Indicate if the trackers were stopped correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.stop();
return result;
}
#Override
public boolean doDeinitTrackers()
{
// Indicate if the trackers were deinitialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
tManager.deinitTracker(ObjectTracker.getClassType());
return result;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
// Process the Gestures
if (mSampleAppMenu != null && mSampleAppMenu.processEvent(event))
return true;
return mGestureDetector.onTouchEvent(event);
}
boolean isExtendedTrackingActive()
{
return mExtendedTracking;
}
final public static int CMD_BACK = -1;
final public static int CMD_EXTENDED_TRACKING = 1;
final public static int CMD_AUTOFOCUS = 2;
final public static int CMD_FLASH = 3;
final public static int CMD_CAMERA_FRONT = 4;
final public static int CMD_CAMERA_REAR = 5;
final public static int CMD_DATASET_START_INDEX = 6;
// This method sets the menu's settings
private void setSampleAppMenuSettings()
{
SampleAppMenuGroup group;
group = mSampleAppMenu.addGroup("", false);
group.addTextItem(getString(R.string.menu_back), -1);
group = mSampleAppMenu.addGroup("", true);
group.addSelectionItem(getString(R.string.menu_extended_tracking),
CMD_EXTENDED_TRACKING, false);
group.addSelectionItem(getString(R.string.menu_contAutofocus),
CMD_AUTOFOCUS, mContAutofocus);
mFlashOptionView = group.addSelectionItem(
getString(R.string.menu_flash), CMD_FLASH, false);
CameraInfo ci = new CameraInfo();
boolean deviceHasFrontCamera = false;
boolean deviceHasBackCamera = false;
for (int i = 0; i < Camera.getNumberOfCameras(); i++)
{
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
deviceHasFrontCamera = true;
else if (ci.facing == CameraInfo.CAMERA_FACING_BACK)
deviceHasBackCamera = true;
}
if (deviceHasBackCamera && deviceHasFrontCamera)
{
group = mSampleAppMenu.addGroup(getString(R.string.menu_camera),
true);
group.addRadioItem(getString(R.string.menu_camera_front),
CMD_CAMERA_FRONT, false);
group.addRadioItem(getString(R.string.menu_camera_back),
CMD_CAMERA_REAR, true);
}
group = mSampleAppMenu
.addGroup(getString(R.string.menu_datasets), true);
mStartDatasetsIndex = CMD_DATASET_START_INDEX;
mDatasetsNumber = mDatasetStrings.size();
group.addRadioItem("Stones & Chips", mStartDatasetsIndex, true);
group.addRadioItem("Tarmac", mStartDatasetsIndex + 1, false);
// group.addRadioItem("my_first", mStartDatasetsIndex + 2, false);
mSampleAppMenu.attachMenu();
}
#SuppressLint("NewApi") #Override
public boolean menuProcess(int command)
{
boolean result = true;
switch (command)
{
case CMD_BACK:
finish();
break;
case CMD_FLASH:
result = CameraDevice.getInstance().setFlashTorchMode(!mFlash);
if (result)
{
mFlash = !mFlash;
} else
{
showToast(getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
Log.e(LOGTAG,
getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
}
break;
case CMD_AUTOFOCUS:
if (mContAutofocus)
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_NORMAL);
if (result)
{
mContAutofocus = false;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_off));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_off));
}
} else
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
{
mContAutofocus = true;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_on));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_on));
}
}
break;
case CMD_CAMERA_FRONT:
case CMD_CAMERA_REAR:
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
vuforiaAppSession.stopCamera();
try
{
vuforiaAppSession
.startAR(command == CMD_CAMERA_FRONT ? CameraDevice.CAMERA.CAMERA_FRONT
: CameraDevice.CAMERA.CAMERA_BACK);
} catch (SampleApplicationException e)
{
showToast(e.getString());
Log.e(LOGTAG, e.getString());
result = false;
}
doStartTrackers();
break;
case CMD_EXTENDED_TRACKING:
for (int tIdx = 0; tIdx < mCurrentDataset.getNumTrackables(); tIdx++)
{
Trackable trackable = mCurrentDataset.getTrackable(tIdx);
if (!mExtendedTracking)
{
if (!trackable.startExtendedTracking())
{
Log.e(LOGTAG,
"Failed to start extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
} else
{
if (!trackable.stopExtendedTracking())
{
Log.e(LOGTAG,
"Failed to stop extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
}
}
if (result)
mExtendedTracking = !mExtendedTracking;
break;
default:
if (command >= mStartDatasetsIndex
&& command < mStartDatasetsIndex + mDatasetsNumber)
{
mSwitchDatasetAsap = true;
mCurrentDatasetSelectionIndex = command
- mStartDatasetsIndex;
}
break;
}
return result;
}
private void showToast(String text)
{
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle pSavedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(pSavedInstanceState);
}
#Override
public EngineOptions onCreateEngineOptions() {
final org.andengine.engine.camera.Camera camera = new org.andengine.engine.camera.Camera(0, 0, Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT), camera);
}
private void updateText() {
final String string = this.mEditText.getText().toString();
this.mText.setText(string);
final float left = (this.mText.getWidth() * 0.5f) - (this.mText.getLineWidthMaximum() * 0.5f);
this.mLeft.setPosition(left, 0, left, Demo.CAMERA_HEIGHT);
final float right = (this.mText.getWidth() * 0.5f) + (this.mText.getLineWidthMaximum() * 0.5f);
this.mRight.setPosition(right, 0, right, Demo.CAMERA_HEIGHT);
}
#Override
protected int getLayoutID() {
// TODO Auto-generated method stub
return R.layout.camera_overlay;
}
#Override
protected int getRenderSurfaceViewID() {
// TODO Auto-generated method stub
return R.id.textbreakexample_rendersurfaceview;
}
#Override
protected void onSetContentView() {
// TODO Auto-generated method stub
super.onSetContentView();
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
}
I am using andEngine for Developing game and I also use vuforia for AR (Augmented Reality).But if i combine both the codes then i getting error as surfaceview null.
**and if it's not supported then what is the use for augmented reality object tracking in andenginre **

How to execute/write all characteristics in a loop in ble in android

How to write all writeCharacteristics in a loop in ble in android.code is as follows
in this method i pass 3 writecharacteristic() and only one is write and others are ignored.
if (beartoggle.isChecked()) {
if (mDeviceLight.equalsIgnoreCase("on") && mDeviceAlarm.equalsIgnoreCase("on")) {
byte[] val = {1};
if (check_port_1 == 1) {
mBluetoothLeService.writeCharacteristic(val, 1);
}
if (check_port_2 == 1) {
mBluetoothLeService.writeCharacteristic(val, 2);
}
if (find_me == 1) {
mBluetoothLeService.writeCharacteristic(val, 3);
}
}
}
and someone is saying use public void onReliableWriteCompleted() and check if port1 is written then go to port2 and then findme. This method will help me, if yes then how ? Please send me clear details and following is my writeCharacteristic()
public boolean writeCharacteristic(byte value[], int type) {
//check mBluetoothGatt is available
if (mBluetoothGatt == null) {
Log.e(TAG, "lost connection");
return false;
}
BluetoothGattService Service = mBluetoothGatt.getService(UUID_SIMPLESERVICE);
if (Service == null) {
Log.e(TAG, "service not found!");
return false;
}
BluetoothGattCharacteristic charac1 = null;
BluetoothGattCharacteristic charac2 = null;
BluetoothGattCharacteristic charac3 = null;
boolean status1 = false, status2 = false, status3 = false;
Log.v("___TYPE___", "________1______________" + (type == 1));
Log.v("___TYPE___", "________2______________" + (type == 2));
Log.v("___TYPE___", "________3______________" + (type == 3));
onReliableWriteCompleted(status1);
onReliableWriteCompleted(status2);
onReliableWriteCompleted(status3);
if (type == 1) {
charac1 = Service.getCharacteristic(UUID_PORT1);
charac1.setValue(value);
status1 = mBluetoothGatt.writeCharacteristic(charac1);
Log.v("________BLESERVICE____", "___WRITE CHARATERISTICS STATUS:_________" + status1);
onReliableWriteCompleted(status1);
} else if (type == 2) {
charac2 = Service.getCharacteristic(UUID_PORT2);
charac2.setValue(value);
status2 = mBluetoothGatt.writeCharacteristic(charac2);
onReliableWriteCompleted(status2);
Log.v("________BLESERVICE_______", "___WRITE CHARACTERISTICS STATUS_______" + status2);
} else if (type == 3) {
charac3 = Service.getCharacteristic(UUID_FINDME);
charac3.setValue(value);
status3 = mBluetoothGatt.writeCharacteristic(charac3);
onReliableWriteCompleted(status3);
Log.v("__________BLESERVICE_________", "___WRITE CHARACTERISTICS STATUS_____" + status3);
}
if (charac1 == null && charac2 == null && charac3 == null) {
Log.e(TAG, "char not found!");
return false;
}
Log.v("___TYPE___", "______________________" + type);
return status1 && status2 && status3;
}
call BluetoothLeService.getSupportedGattServices(), you will get a list of services. Iterate through it and call BluetoothGattService.getCharacteristics(). You will again get a list, you can iterate through it.
For more info, you can refer this

Does not skip to main activity

Hi all I am using a splash activity for first time or he is logged out from my app. But this appear frequently on Samsung galaxy S2. This my activity onCreate() method code
private static EditText serverIP = null;
String mMDCServerIP = "";
String skipSplashScreenStatus = null;
String mSplashScreenRunningStatus = null;
String mDeniedStatusFromServer = null;
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
/** Get the MDC IP **/
Log.d("splash","1111111111111111");
skipSplashScreenStatus = Config.getSetting(getApplicationContext(),"SPLASHSTATUS");
mSplashScreenRunningStatus = Config.getSetting(getApplicationContext(),"SPLASHACTIVITYRUNNINGSTATUS");
mDeniedStatusFromServer = Config.getSetting(getApplicationContext(),"DENYSTATUS");
if(skipSplashScreenStatus == null || skipSplashScreenStatus.length() == 0)
{
Config.setSetting(getApplicationContext(),"DENYSTATUS","false");
}
/** If SPLASHSTATUS does not exist then store the SPLASHSTATUS as false**/
if(skipSplashScreenStatus == null || skipSplashScreenStatus.length() == 0)
{
Config.setSetting(getApplicationContext(),"SPLASHSTATUS","false");
}
if(mSplashScreenRunningStatus == null || mSplashScreenRunningStatus.length() == 0)
{
Config.setSetting(getApplicationContext(),"SPLASHACTIVITYRUNNINGSTATUS","yes");
}
Log.d("splash","222222222222222222");
Log.d("splash","skipSplashScreenStatus : "+skipSplashScreenStatus);
skipSplashScreenStatus = Config.getSetting(getApplicationContext(),"SPLASHSTATUS");
if(skipSplashScreenStatus!= null && skipSplashScreenStatus.equalsIgnoreCase("yes"))
{
Log.d("splash","inside if condition");
skipSplashScreen();
}
else{
Log.d("splash","inside else condition");
setContentView(R.layout.splash_screen);
Log.d("SPLASH","33333333333333");
serverIP = (EditText) findViewById(R.id.splash_server_ip);
/** Get the MDC IP **/
mMDCServerIP = Config.getSetting(getApplicationContext(),"IPADDR");
/** If MDC IP does not exist then store the IP as 0.0.0.0**/
if(mMDCServerIP == null || mMDCServerIP.length() == 0)
{
Config.setSetting(getApplicationContext(),"IPADDR","0.0.0.0");
}
serverIP.setOnEditorActionListener(new EditText.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
Config.setSetting(getApplicationContext(),"SPLASHSTATUS","yes");
Config.setSetting(getApplicationContext(),"SPLASHACTIVITYRUNNINGSTATUS","no");
skipSplashScreen();
}}}}
Here is the code for skipSplashScreen();
private void skipSplashScreen()
{
try{
Log.d("splash","inside skipSplashScreen 111");
CommandHandler.mStopSendingKeepAlive = false;
Log.d("splash","inside skipSplashScreen 222");
startActivity(new Intent(getApplicationContext() ,SecondTest.class));
}
catch(Exception e)
{
Log.d("splash","Exception in skipSplashScreen 333");
Log.d("splash",e.getMessage());
}
}
Once i dig more into code it seems control is skipSplashScreen() method but not starting second activity. May i know what can be the reason.
Try this, when starting the activity, use Activity.this instead of getApplicationContext()
private void skipSplashScreen()
{
try{
Log.d("splash","inside skipSplashScreen 111");
CommandHandler.mStopSendingKeepAlive = false;
Log.d("splash","inside skipSplashScreen 222");
startActivity(new Intent(SplashScreen.this ,SecondTest.class));
}
catch(Exception e)
{
Log.d("splash","Exception in skipSplashScreen 333");
Log.d("splash",e.getMessage());
}
}

how to write in edit text using custom keyboard application in android

i am doing an application that needs a special keyboard and i can get the text into a edit text by pressing the keys.
public class SecondActivity extends Activity implements
OnKeyboardActionListener, OnKeyListener {
private static final String TAG = SecondActivity.class.getName();
private EditText editText1, editText2, editText3;
private InputMethodManager imm;
private String mWordSeparators;
private StringBuilder mComposing = new StringBuilder();
private KeyboardView keyboardView;
private Keyboard keyboard;
private Keyboard miKeyboard;
private boolean mCapsLock;
private long mLastShiftTime;
private boolean mCompletionOn;
private long mMetaState;
private CompletionInfo[] mCompletions;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Log.d("cambio estado", "onDestroy");
}
});
Button button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Log.d("cambio estado", "onDestroy");
}
});
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText1.getWindowToken(), 0);
imm.hideSoftInputFromWindow(editText2.getWindowToken(), 0);
imm.hideSoftInputFromWindow(editText3.getWindowToken(), 0);
mWordSeparators = getResources().getString(R.string.word_separators);
keyboardView = (KeyboardView) findViewById(R.id.keyboardView);
keyboard = new Keyboard(this, R.xml.qwerty);
miKeyboard = new Keyboard(this,R.xml.qwerty);
keyboardView.setKeyboard(keyboard);
keyboardView.setEnabled(true);
keyboardView.setPreviewEnabled(true);
keyboardView.setOnKeyListener(this);
keyboardView.setOnKeyboardActionListener(this);
}
public void onStartInput(EditorInfo attribute, boolean restarting) {
mComposing.setLength(0);
updateCandidates();
if (!restarting) {
mMetaState = 0;
}
mCompletionOn = false;
mCompletions = null;
switch (attribute.inputType & InputType.TYPE_MASK_CLASS) {
case InputType.TYPE_CLASS_NUMBER:
case InputType.TYPE_CLASS_DATETIME:
keyboard = miKeyboard;
break;
case InputType.TYPE_CLASS_PHONE:
keyboard = miKeyboard;
break;
case InputType.TYPE_CLASS_TEXT:
keyboard = miKeyboard;
updateShiftKeyState(attribute);
break;
default:
keyboard = miKeyboard;
updateShiftKeyState(attribute);
}
}
public void onDisplayCompletions(CompletionInfo[] completions) {
if (mCompletionOn) {
if (completions == null) {
return;
}
List<String> stringList = new ArrayList<String>();
for (int i = 0; i < completions.length; i++) {
CompletionInfo ci = completions[i];
if (ci != null) stringList.add(ci.getText().toString());
}
}
}
private boolean translateKeyDown(int keyCode, KeyEvent event) {
mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState,
keyCode, event);
int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState));
mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
InputConnection ic = getCurrentInputConnection();
if (c == 0 || ic == null) {
return false;
}
if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) {
c = c & KeyCharacterMap.COMBINING_ACCENT_MASK;
}
if (mComposing.length() > 0) {
char accent = mComposing.charAt(mComposing.length() -1 );
int composed = KeyEvent.getDeadChar(accent, c);
if (composed != 0) {
c = composed;
mComposing.setLength(mComposing.length()-1);
}
}
onKey(c, null);
return true;
}
private void hideDefaultKeyboard() {
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private void handleShift() {
checkToggleCapsLock();
keyboardView.setShifted(mCapsLock || !keyboardView.isShifted());
}
private void checkToggleCapsLock() {
long now = System.currentTimeMillis();
if (mLastShiftTime + 800 > now) {
mCapsLock = !mCapsLock;
mLastShiftTime = 0;
} else {
mLastShiftTime = now;
}
}
private void updateCandidates() {
if (!mCompletionOn) {
if (mComposing.length() > 0) {
ArrayList<String> list = new ArrayList<String>();
list.add(mComposing.toString());
}
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
keyboardView.closing();
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (keyboardView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
}
else {
getCurrentInputConnection().commitText(
String.valueOf((char) primaryCode), 1);
}
}
public void onText(CharSequence text) {
Log.d(TAG, "onText? \"" + text + "\"");
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
if (mComposing.length() > 0) {
commitTyped(ic);
}
ic.commitText(text, 0);
ic.endBatchEdit();
updateShiftKeyState((EditorInfo) getCurrentInputEditorInfo());
}
private void updateShiftKeyState(EditorInfo attr) {
if (attr != null
&& keyboardView != null && keyboard == keyboardView.getKeyboard()) {
int caps = 0;
EditorInfo ei = (EditorInfo) getCurrentInputEditorInfo();
if (ei != null && ei.inputType != InputType.TYPE_NULL) {
caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType);
}
keyboardView.setShifted(mCapsLock || caps != 0);
}}
private void commitTyped(InputConnection inputConnection) {
if (mComposing.length() > 0) {
inputConnection.commitText(mComposing, mComposing.length());
mComposing.setLength(0);
updateCandidates();
}
}
private String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
private void handleBackspace() {
final int length = mComposing.length();
if (length > 1) {
mComposing.delete(length - 1, length);
getCurrentInputConnection().setComposingText(mComposing, 1);
updateCandidates();
} else if (length > 0) {
mComposing.setLength(0);
getCurrentInputConnection().commitText("", 0);
updateCandidates();
} else {
keyDownUp(KeyEvent.KEYCODE_DEL);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
private InputConnection getCurrentInputConnection() {
return getCurrentInputConnection();
}
private EditorInfo getCurrentInputEditorInfo() {
return getCurrentInputEditorInfo();
}
#Override
public void swipeUp() {
Log.d(TAG, "swipeUp");
}
#Override
public void swipeRight() {
Log.d(TAG, "swipeRight");
}
#Override
public void swipeLeft() {
Log.d(TAG, "swipeLeft");
handleBackspace();
}
#Override
public void swipeDown() {
Log.d(TAG, "swipeDown");
handleClose();
}
#Override
public void onRelease(int primaryCode) {
Log.d(TAG, "onRelease? primaryCode=" + primaryCode);
}
#Override
public void onPress(int primaryCode) {
Log.d(TAG, "onPress? primaryCode=" + primaryCode);
}
#Override
public void onKey(int primaryCode, int[] keyCodes) {
Log.d(TAG, "onKey? primaryCode=" + primaryCode);
int n1 = 0; // -1 count
for (int keyCode : keyCodes) {
if (keyCode == -1) {
n1++;
continue;
}
Log.v(TAG, "keyCode=" + keyCode);
}
Log.v(TAG, "keyCode=-1 *" + n1);
if (isWordSeparator(primaryCode)) {
if (mComposing.length() > 0) {
commitTyped(getCurrentInputConnection());
}
sendKey(primaryCode);
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (primaryCode == Keyboard.KEYCODE_DELETE) {
handleBackspace();
} else if (primaryCode == Keyboard.KEYCODE_SHIFT) {
handleShift();
} else if (primaryCode == Keyboard.KEYCODE_CANCEL) {
handleClose();
} else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE
&& keyboardView != null) {
Keyboard current = keyboardView.getKeyboard();
keyboardView.setKeyboard(current);
} else {
handleCharacter(primaryCode, keyCodes);
}
}
private void sendKey(int keyCode) {
switch (keyCode) {
case '\n':
keyDownUp(KeyEvent.KEYCODE_ENTER);
break;
default:
if (keyCode >= '0' && keyCode <= '9') {
keyDownUp(keyCode - '0' + KeyEvent.KEYCODE_0);
} else {
getCurrentInputConnection().commitText(String.valueOf((char) keyCode), 1);
}
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && keyboardView != null) {
if (keyboardView.handleBack()) {
return true;
}
}
break;
case KeyEvent.KEYCODE_DEL:
if (mComposing.length() > 0) {
onKey(Keyboard.KEYCODE_DELETE, null);
return true;
}
break;
case KeyEvent.KEYCODE_ENTER:
return false;
default:
if (mCapsLock) {
if (keyCode == KeyEvent.KEYCODE_SPACE
&& (event.getMetaState()&KeyEvent.META_ALT_ON) != 0) {
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.clearMetaKeyStates(KeyEvent.META_ALT_ON);
keyDownUp(KeyEvent.KEYCODE_A);
keyDownUp(KeyEvent.KEYCODE_N);
keyDownUp(KeyEvent.KEYCODE_D);
keyDownUp(KeyEvent.KEYCODE_R);
keyDownUp(KeyEvent.KEYCODE_O);
keyDownUp(KeyEvent.KEYCODE_I);
keyDownUp(KeyEvent.KEYCODE_D);
return true;
}
}
if (translateKeyDown(keyCode, event)) {
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
private void keyDownUp(int keyEventCode) {
getCurrentInputConnection().sendKeyEvent(
new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
getCurrentInputConnection().sendKeyEvent(
new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
hideDefaultKeyboard();
Log.d(TAG, "onKey? keyCode=" + keyCode);
return false;
}
}
In your Xml file, Inside the editText tag you find something like android:inputType attribute. you can specify different types of input types like textEmail, phoneNumber, textPassword.
There are so many types, if you specify the input type attribute, it will show custom keyboard according to input type,
If your editText input type is a phoneNumber, then it will show Num KeyPad
If your editText input type is a textPassword, then it will show Character Keypad
Like this, you can have more custom keypad / keyboard
For Password keypad,
<EditText android:id=..........
android:inputType="textPassword" />
For Numeric Keypad
<EditText android:id=..........
android:inputType="number" />
have you declared it in manifest like
<service
android:name="TamilSoftKeyboard"
android:permission="android.permission.BIND_INPUT_METHOD">
<intent-filter>
<action android:name="android.view.InputMethod" />
</intent-filter>
<meta-data
android:name="android.view.im"
android:resource="#xml/method" />
</service>

Categories

Resources