I have a activity am using a boolean condition to check some thing .if the boolean condition Satisfy i need to Go to The next Page. But When The condition Satisfy the Device get crash With NullPointerException Am giving The Code Below
The Boolean Condition
boolean check()
{
boolean matches=false;
int falseFlag=0;
if(cc.length==picarray.length)
{
for (int i=0;i<cc.length;i++)
{
if(cc[i].equals(picarray[i]))
{
//---The Database Value Stored in Array is modified---
xmin=X[i]-25;
xmax=X[i]+25;
ymin=Y[i]-25;
ymax=Y[i]+25;
//---Check Whether The Selected Password Is Inside The Array Values---
if(xmin<realx[i]&&realx[i]<xmax)
{
System.out.println("TRUE");
}
else
{
falseFlag++;
System.out.println("FALSE");
}
if(ymin<realy[i]&&realy[i]<ymax)
{
System.out.println("TRUE");
}
else
{
falseFlag++;
System.out.println("FALSE");
}
}
else
{
falseFlag++;
}
}
}
else
{
falseFlag++;
}
if(falseFlag==0)
{
matches=true;
}
System.out.println("Authentication returns "+matches);
return matches;
}
in button click
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(check())
{
Intent sa=new Intent(Test.class,Test2.class);
startActivity(sa);
System.out.println("U R AUTHENTICATED");
}
else
{
System.out.println("INVALID USER");
Toast.makeText(getApplicationContext(), "INVALID USER", Toast.LENGTH_LONG).show();
}
}
});
try this,
Intent sa=new Intent(getApplicationContext(),Test2.class);
basically intent needs context and not a class...
i doub't this (Intent sa=new Intent(Test.class,Test2.class);) will compile
The first argument is a Context so when you create the intent, it should be:
Intent sa=new Intent(Test.this,Test2.class);
instead of
Intent sa=new Intent(Test.class,Test2.class);
This should also work:
Intent sa=new Intent(v.getContext(),Test2.class);
Intent sa=new Intent(Test.class,Test2.class);
The first parameter should be Test.this(Context), is it not throwing a Compile-time error ??
Related
I have need some help to achieve the following:
When I click on my previous-button I want the application to go to the previous page without losing my data. I already added the previous-button to the application, but when I click it my application goes to the main page instead of the previous page.
My code:
Button next,previous;
next = (Button)findViewById(R.id.work_next);
previous = (Button)findViewById(R.id.work_previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignUP = new Intent(getApplicationContext(), filldetails.class);
startActivity(intentSignUP);
finish();
}
});
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean allValues = true;
String comp="",desg="",fromdate="",todate="",role_d="",technologies_used="";
if(companyName.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
comp= companyName.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(designation.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
desg = designation.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(fromDate.getText().toString().length()<8 || fromDate.getText().toString().length()>10 ||fromDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
fromdate = fromDate.getText().toString();
}
if(toDate.getText().toString().length()<8 || toDate.getText().toString().length()>10 ||toDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
todate = toDate.getText().toString();
}
if(role_desc.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
role_d = role_desc.getText().toString();
}
if(technologiesUsed.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
technologies_used = technologiesUsed.getText().toString();
}
if(allValues)
{
Intent moveToNext = new Intent(getApplicationContext(),skills.class);
moveToNext.putExtra("comp_name",comp);
moveToNext.putExtra("desc",desg);
moveToNext.putExtra("role_d",role_d);
moveToNext.putExtra("from_date",fromdate);
moveToNext.putExtra("to_date",todate);
moveToNext.putExtra("technologies_used",technologies_used);
moveToNext.putExtra("iscurrent",isCurrent.isChecked());
moveToNext.putExtra("aboutme",getIntent().getStringExtra("aboutme"));
moveToNext.putExtra("address",getIntent().getStringExtra("address"));
startActivity(moveToNext);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Please provide all values", Toast.LENGTH_SHORT).show();
}
}
});
}
You don't need to start the activity to go to previous activity (if you haven't called finish() on that), just close the current activity and it will go to previous activity and data will be intact.
Change your onClick method of previous button like this
#Override
public void onClick(View v) {
finish();
}
Note: If you have closed the previous activity by calling finish() then remove that code, otherwise data will not be intact without modifying your code in that activity.
This if-else statement I am using it onClick method of Android code.
if (input == null){
dispError();
}else{
startAct();
}
when value is true or false startAct() gets implemented;
if (input != null){
dispError();
}else{
startAct();
}
when value is true or false dispError() gets implemented;
input is a string.
actual code of my program:
#Override
public void onClick(View view) {
// Launching Display Meaning Activity
meaning = (EditText) findViewById(R.id.editText1);
input = meaning.getText().toString();
if (input == null){
dispError();
}else{
startAct();
}
}
public void startAct(){
Intent intent =new Intent("com.dictionary.khasi_english.DisplayMeaningActivity");
intent.setClass(MainActivity.this, DisplayMeaningActivity.class);
intent.putExtra(MEANING_INPUT, input);
startActivity(intent);
}
public void dispError(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("ERROR");
builder.setMessage("Please enter a Word.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
}
meaning.getText().toString() will never return null. However, it can return "", an empty string. Use the following code to check against that:
if(input.isEmpty()) {
dispError();
else {
startAct();
}
It is because input, as you said, could be 'true' or 'false'. In both cases input is not null. If you want your if-statement works, you should try:
if(input.equals("true")) {
startAct();
else {
dispError();
}
Assuming you are trying to check whether the user put in any text, you should use TextUtils.isEmpty, which checks against both null and empty strings:
if(TextUtils.isEmpty(input)) {
dispError();
} else {
startAct();
}
if input is a string
try to use input.length to check if it is empty
if(input.length==0)
displayerror();
because if input=""then it is not null.
you can use TextUtils.isEmpty()
I am trying to create an application that reads an NFC tag and checks the tag against strings in a string array and then sets the text on another activity. I have got it working so that it checks if the string exists and sets the text in the new activity, but I want to be able to specify which string I want it to check against within the array, because there will be multiple strings in the NFC tag that I want to then display in the new activity. I have tried this for it:
result == getResources().getString(R.string.test_dd)
Here is the relevant code:
String[] dd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dd = getResources().getStringArray(R.array.device_description);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if(doesArrayContain(dd, result)) {
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(800);
Intent newIntent = new Intent(getApplicationContext(), TabsTest.class);
Bundle bundle1 = new Bundle();
bundle1.putString("key", result);
newIntent.putExtras(bundle1);
startActivity(newIntent);
Toast.makeText(getApplicationContext(), "NFC tag written successfully!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), result + " is not in the device description!", Toast.LENGTH_SHORT).show();
}
}
}
EDIT:
Here is the method used and please can anyone help me with this problem:
public static boolean doesArrayContain(String[] array, String text) {
for (String element : array) {
if(element != null && element.equalsIgnoreCase(text)) {
return true;
}
}
return false;
}
For comparing equality of strings (and other objects) use the equals() method. == compares identity of objects (same string object).
Here is the solution that I found:
Create a new method:
public static boolean stringCaseInsensitive(String string, String result) {
if(string != null && string.equalsIgnoreCase(result)) {
return true;
}
return false;
}
And call it in like this:
if(stringCaseInsensitive(getResources().getString(R.string.test_dd), result))
{
Intent newIntent = new Intent(getApplicationContext(), TabsTest.class);
Bundle bundle1 = new Bundle();
bundle1.putString("key", result);
newIntent.putExtras(bundle1);
startActivity(newIntent);
Toast.makeText(getApplicationContext(), "NFC tag written successfully!", Toast.LENGTH_SHORT).show();
}
else{
}
I am pulling my hair out! At one point in the last week, I had this working.
I have an Android app that I am trying to add in-ap billing to. I followed the sample TrivialDrive, and my code worked a few times. Now it doesn't.
I am creating a simple trivia game that has a number of free questions, and the option to upgrade to get more questions. When the user completes the list of free questions, they are taken to a "Game Over" screen where they can erase their answers and start again, or upgrade.
When I click the "Upgrade" button, I can make a successful purchase, but as soon as the Google "Payment Successful" dialog goes away, my activity is destroyed and I am sent back to my main activity.
When I try to go back and do my purchase again, my code catches the error ("You already own this item") and handles it appropriately. My code explains to the user that they already own the upgrade, and allows them to click a button to continue playing. So it looks like the OnIabPurchaseFinishedListener is firing at this point.
I have updated the Google helper code with the latest files.
Any help or suggestions as to where to look for answers is much appreciated.
Thanks.
This is the relevant code for my activity:
public class GameOverActivity extends BaseActivity
{
private IabHelper mHelper;
private String m_base64EncodedPublicKey;
private static String THE_UPGRADE_SKU = "upgrade52";
public static int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_over);
setTitle("Game Over");
Button butPlay = (Button) findViewById(R.id.buttonPlay);
butPlay.setVisibility(View.INVISIBLE);
PrepareIAB();
}
#Override
protected void onResume()
{
super.onResume();
CURRENT_ACTIVITY = ACTIVITY_GAME_OVER;
SetMainText();
}
#Override
protected void onDestroy()
{
super.onDestroy();
try
{
if (mHelper != null)
{
mHelper.dispose();
mHelper = null;
}
}
catch (Exception e)
{
}
}
private void PrepareIAB()
{
m_base64EncodedPublicKey = "MyKey";
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, m_base64EncodedPublicKey);
mHelper.enableDebugLogging( true, TAG);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
{
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess())
{
ShowMessage("There was an error connecting to the Google Play Store.");
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
try
{
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data))
{
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
super.onActivityResult(requestCode, resultCode, data);
}
else
{
// Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
catch (Exception e)
{
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener =
new IabHelper.OnIabPurchaseFinishedListener()
{
public void onIabPurchaseFinished(IabResult result, Purchase purchase)
{
try
{
if (result.isFailure())
{
if (result.mResponse==7)
{
UpgradeComplete();
ShowMessage("Thank you for upgrading.\r\n\r\nThis version has 400 more questions.");
}
else
{
ShowMessage("Error purchasing: " + String.valueOf(result.mResponse));
UpgradeError();
return;
}
}
else if (purchase.getSku().equals(THE_UPGRADE_SKU))
{
UpgradeComplete();
ShowMessage("Thank you for upgrading.\r\n\r\nThis version has 400 more questions.");
}
else
{
ShowMessage("Something else happened. ");
}
}
catch (Exception e)
{
Log.e(TAG, e.getLocalizedMessage());
}
}
};
private void HideUpgrade()
{
try
{
Button btnUpgrade = (Button) findViewById(R.id.buttonUpgrade);
if (btnUpgrade != null)
{
btnUpgrade.setVisibility(View.INVISIBLE);
}
TextView txtMessage = (TextView) findViewById(R.id.txtUpgradeFromGameOver);
if (txtMessage!=null)
{
txtMessage.setVisibility(View.INVISIBLE);
}
}
catch (Exception e)
{
}
}
public void onQuitButtonClick(View view)
{
finish();
}
public void onResetDBButtonClick(View view)
{
ConfirmResetDatabase();
}
private void ConfirmResetDatabase()
{
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
ResetDatabase();
Intent gameActivity = new Intent(getApplicationContext(), GameActivity.class);
gameActivity.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
// startActivityForResult(gameActivity, ACTIVITY_GAME);
startActivity(gameActivity);
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to erase your score and start over?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
}
public void onUpgradeButtonClick(View view)
{
try
{
if (mHelper != null)
{
mHelper.launchPurchaseFlow(this, THE_UPGRADE_SKU, 10001, mPurchaseFinishedListener, m_TriviaAppInstance.AppInstallID());
}
else
{
ShowMessage("Unable to connect to Google Play Store.");
}
}
catch (Exception e)
{
ShowMessage("Unable to connect to Google Play Store.");
SendErrorMessage(e.getLocalizedMessage());
}
}
private void UpgradeComplete()
{
try
{
HideUpgrade();
Button butPlay = (Button) findViewById(R.id.buttonPlay);
if (butPlay!=null)
{
butPlay.setVisibility(View.VISIBLE);
}
TextView txtReset = (TextView) findViewById(R.id.txtGameOverRestDB);
if (txtReset!=null)
{
txtReset.setVisibility(View.INVISIBLE);
}
Button btnReset = (Button)findViewById(R.id.buttonResetDB);
if (btnReset!=null)
{
btnReset.setVisibility(View.INVISIBLE);
}
m_TriviaAppInstance.SetUpgradedStatus(true);
}
catch (Exception e)
{
}
//
}
private void UpgradeError()
{
try
{
Button butUpgrade;
butUpgrade = (Button) findViewById(R.id.buttonUpgrade);
butUpgrade.setVisibility(View.INVISIBLE);
TextView txtMessage = (TextView) findViewById(R.id.txtUpgradeScreen);
txtMessage.setText(R.string.upgradeScreenTextError);
}
catch (Exception e)
{
}
}
public void onPlayButtonClick(View view)
{
Intent myIntent = new Intent(view.getContext(), GameActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(myIntent, ACTIVITY_GAME);
}
public void SetMainText()
{
TextView txt = (TextView) findViewById(R.id.txtScoreGlobal);
txt.setText(Integer.toString(m_TriviaAppInstance.getGlobal()) + "%");
SetPlayerScore(1);
if (m_TriviaAppInstance.getUpgradedStatus() == true)
{
HideUpgrade();
}
}
}
FYI: I think I have this figured out - for anyone else that may come across it.
The activity that I was using to launch "In App Billing" was called with a "FLAG_ACTIVITY_NO_HISTORY". I did this because I didn't want the user to be able to click to go back to this "Game Over" activity.
BUT, this causes grief with "In App Billing". So, make sure you don't try to launch "In App Billing" from an activity that has had the "FLAG_ACTIVITY_NO_HISTORY" set.
My original code:
private void GameOver()
{
m_TriviaAppInstance.setGameOver(true);
Intent gameOver = new Intent(getApplicationContext(), GameOverActivity.class);
gameOver.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(gameOver);
}
Updated code:
private void GameOver()
{
m_TriviaAppInstance.setGameOver(true);
Intent gameOver = new Intent(getApplicationContext(), GameOverActivity.class);
startActivity(gameOver);
}
Peace
I'm not high enough to comment, but bless you. I had
android:noHistory="true"
set in AndroidManifest.xml for my activity and was experiencing the same problem.
Took it out and IAB is working. Yay!
Do not forget that your IabHelper.OnIabPurchaseFinishedListener is called on a different thread and before onResume() is called on your Activity!
So your UpgradeComplete() or UpgradeError() can cause a crash on older devices (Crashed every time on my Gingerbread Sony Xperia Mini Pro and worked without any trouble on Samsung Galaxy S4 (Android 4.2.2)
Caused a 3 day delay on my game..
I have created a Login activity which uses another class - LoginService which is an AsyncTask for the network communication.
public void onClick(View view) {
if (editTextPassword.getText().toString() != null & editTextUsername.getText().toString() != null){
new LoginService(editTextUsername.getText().toString(), editTextPassword.getText().toString()).execute();
if(loginSuccess!=false){
//Used to move to the Cases Activity
Intent casesActivity = new Intent(getApplicationContext(), CasesActivity.class);
startActivity(casesActivity);
}else{
Toast.makeText(getApplicationContext(),"Incorrect Details", Toast.LENGTH_LONG).show();
}
}
else{
//Display Toaster for error
Toast.makeText(getApplicationContext(),"Please enter your details", Toast.LENGTH_LONG).show();
}
}
Before the LoginService has finished executing, the activity has already moved to another activity via the Intent variable. I do not understand why. The idea of the LoginService is to validate the credentials of the user. If it returns true, then it can switch to the other activity.
You do not want to do this in this way. The .execute() will begin as soon as possible, but there is no guarantee (and perhaps guaranteed not to) that it will get your loginSuccess value back to you in time.
Everything after new LoginService(...).execute(); should be moved into onPostExecute():
private Context mContext = null;
public void setContext(Context context) {
mContext = context;
}
#Override
protected void onPostExecute(Void result) {
if(loginSuccess!=false){
//Used to move to the Cases Activity
Intent casesActivity = new Intent(mContext, CasesActivity.class);
startActivity(casesActivity);
}else{
Toast.makeText(mContext,"Incorrect Details", Toast.LENGTH_LONG).show();
}
}
Then, you have to call setContext() like so:
LoginService service = new LoginService(editTextUsername.getText().toString(), editTextPassword.getText().toString());
service.setContext(getApplicationContext());
service.execute();
You should move
Intent casesActivity = new Intent(getApplicationContext(), CasesActivity.class);
startActivity(casesActivity);
}else{
Toast.makeText(getApplicationContext(),"Incorrect Details", Toast.LENGTH_LONG).show();
}
into LoginService's onPostExecute.
In this way you are sure the asynctask has finished its work.
In any case it's quite strange the other activity gets started, it might be because of an old assignement of loginSuccess to true
How to return the result from the asynctask?
Catch the result of AsyncTask from onPostExecute().
#Override
public void onPostExecute(Boolean result)
{
boolean loginSuccess = result;
if(loginSuccess!=false) {
Intent casesActivity = new Intent(getApplicationContext(), CasesActivity.class);
startActivity(casesActivity);
}
else {
Toast.makeText(getApplicationContext(),"Incorrect Details", Toast.LENGTH_LONG).show();
}
}
The data type of result in AsyncTask depends on the 3rd Type parameter.
Sometimes we think execute() method of AsyncTask will return a result which is wrong. It will return an AsyncTask itself