there is a snippet of code of an android app (Android Studio) in Java language I tried to understand,there is number 17 as an index of an array as I highlighted the line code in bold , I tried a lot but I couldn't understand what's that number, here is the snippet code
protected void onPostExecute(String result)
{
**if(result == "0")**
{
Context context = getApplicationContext();
CharSequence text = "Invalid IP address";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
char[] charArray = result.toCharArray();
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
**if(charArray[17]=='0')**
{
CharSequence text = "Invalid Password";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
_logged_in = false;
}
**if(charArray[17]=='1')**
{
CharSequence text = "You logged in successfully";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
_logged_in = true;
startActivity(intent);
}
}
Thanks in advance
Don't use
if(result == "0")
If you are working with a String you should use:
if(result.equals("0"))
Also
if(charArray[17]=='0')
means that charArray is an array and you are getting the element with index=17. Pay attention that the first index is 0.
Related
Following this guide https://developers.google.com/admob/ump/android/quick-start I tried to add everything to my app.
What I did:
link funding choices to admob
added ump to build.gradle
added the app ID to android manifest
set up a dialog for the app in admob and activated it for the app
Then I added this code to my app
ConsentRequestParameters params = new ConsentRequestParameters
.Builder()
.setTagForUnderAgeOfConsent(false)
.build();
consentInformation = UserMessagingPlatform.getConsentInformation(this);
consentInformation.requestConsentInfoUpdate(
this,
params,
new ConsentInformation.OnConsentInfoUpdateSuccessListener() {
#Override
public void onConsentInfoUpdateSuccess() {
// The consent information state was updated.
// You are now ready to check if a form is available.
if (consentInformation.isConsentFormAvailable()) {
loadForm();
}
else {
Context context = getApplicationContext();
CharSequence toastText = "No Form Available";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
},
new ConsentInformation.OnConsentInfoUpdateFailureListener() {
#Override
public void onConsentInfoUpdateFailure(FormError formError) {
// Handle the error.
Context context = getApplicationContext();
CharSequence toastText = "Error";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
});
and
public void loadForm() {
UserMessagingPlatform.loadConsentForm(
this,
new UserMessagingPlatform.OnConsentFormLoadSuccessListener() {
#Override
public void onConsentFormLoadSuccess(ConsentForm consentForm) {
MainActivity.this.consentForm = consentForm;
if(consentInformation.getConsentStatus() == ConsentInformation.ConsentStatus.REQUIRED) {
consentForm.show(
MainActivity.this,
new ConsentForm.OnConsentFormDismissedListener() {
#Override
public void onConsentFormDismissed(#Nullable FormError formError) {
// Handle dismissal by reloading form.
loadForm();
}
});
}
}
},
new UserMessagingPlatform.OnConsentFormLoadFailureListener() {
#Override
public void onConsentFormLoadFailure(FormError formError) {
// Handle the error
}
}
);
}
However, I always end up getting the toast "Error" landing in onConsentInfoUpdateFailure(FormError formError) independet from testing on my mobile phone or in the virtual device (I am in europe btw).
Am I missing something?
Thanks,
Celdri
I had the same issue and I solved it just by configuring properly my adMob account.
I want to show Toast when no results found after searching ,
I made a simple Toast but toast remains for long time and i want it to disappear after short time
this is code
public boolean onQueryTextSubmit(String query) {
final String[] dose = getResources().getStringArray(R.array.doses);
final String[] use = getResources().getStringArray(R.array.uses);
final String[] composition = getResources().getStringArray(R.array.composition);
final TypedArray img = getResources().obtainTypedArray(R.array.img);
for (String search : suggestions)
{
if (query.equals(search)){
for (int i =0; i<suggestions.length; i++){
if (query.equals(suggestions[i])){
Intent intent = new Intent(MainActivity.this,productDetails.class);
int im = img.getResourceId(i,-1);
intent.putExtra("img",im);
intent.putExtra("dose",dose[i]);
intent.putExtra("use",use[i]);
intent.putExtra("composition",composition[i]);
intent.putExtra("title",suggestions[i].toUpperCase());
startActivity(intent);
}
}
}
else if (query!= search){
Toast.makeText(MainActivity.this, "No Results Found", Toast.LENGTH_SHORT).show();
}
}
return false;
}
Your toast is showing in for loop, he is added to queue multiple time, remove it from loop
I am using the toast inside filter class. Here is the code for it
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
expressionlist.clear();
if (charText.length() == 0) {
expressionlist.addAll(arraylist);
} else {
for (Expression wp : arraylist) {
if (wp.getWord().toLowerCase(Locale.getDefault())
.contains(charText)) {
expressionlist.add(wp);
}
}
if(expressionlist.size() == 0){
Toast toast = Toast.makeText(this, "No match found", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
// add all items of expressionlist
expressionlist.addAll(arraylist);
}
}
notifyDataSetChanged();
}
}
I am getting error The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (ListViewAdapter, String, int)
How can I solve this?
You should refer context ie getApplicationContext() or pass the ListViewAdapter's context.
Context can be an Activity or Fragment
Toast toast = Toast.makeText(context, "No match found", Toast.LENGTH_LONG);
The onReceive() in my class listens for SMSs and sends an SMS in reply, everything is working fine but once. After sending SMS the app shuts down with the message "Unfortunately, yourApp has stopped". I want it to remain active. I wonder where I'm missing out. Thanks for help!
public class SMSReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
private static final String TAG="SMSReceiver";
#Override
public void onReceive(Context context,Intent intent){
SmsManager smsManager=SmsManager.getDefault();
int i;
Toast.makeText(context,"Intent recieved",Toast.LENGTH_LONG).show();
Log.i(TAG,"Intent recieved: "+intent.getAction());
String messageContent="";
if (intent.getAction() == SMS_RECEIVED) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
messageContent=messages[i].getMessageBody().toString();
}
if (messages.length > -1 && messageContent.charAt(8)=='#') {
Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
Toast.makeText(context, "Message received from victim: "+messageContent, Toast.LENGTH_LONG).show();
smsManager.sendTextMessage("+919032687185",null,"Request#",null,null);
//Toast.makeText(context, "SMS sent.",Toast.LENGTH_LONG).show();
/*for(i=0;i<7;i++){
MediaPlayer mediaPlayer=MediaPlayer.create(context, R.raw.fire_engine_siren_could_be_police_ambulance_etc);
mediaPlayer.start();
}*/
}
/*else if(messages.length > -1 && messageContent.charAt(6) == '#'){
Log.i(TAG, "Location from patrol" + messages[0].getMessageBody());
Toast.makeText(context, "Message received from ambulance: "+messageContent, Toast.LENGTH_LONG).show();
}*/
}
}
}
}
It seems like you're getting a java.lang.StringIndexOutOfBoundsException and my guess is the culprit is messageContent.charAt(8) because the logcat indicates length=8; index=8
Try using indexOf instead if finding this #'s location is necessary. Its a bit more flexible and won't throw exceptions at you.
My application has the following modules,
To collect users CB location code.
To save that in a database of user's choice, say for example my CB code is 465783 and I can save that as 'College' in my database.
To provide alarm feature, in this module I can give a text input say I give it as 'College' and when the Cell Broadcast is updated if the value college matches alarm is given out.
Now, in my below code I've achieved first 2 modules and also the required database entries, databases search etc, I'm not able to read the updated CB location value.
public class Alarm extends MainActivity {
public String str;
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB " + msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
str += " :";
str += "\n";
}
}
}
EditText user_value;
Button startalarm;
Button stopalarm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
startalarm = (Button) findViewById(R.id.startalarm);
stopalarm = (Button) findViewById(R.id.stopalarm);
user_value = (EditText) findViewById(R.id.user_value);
final Ringtone ringtone;
ringtone = RingtoneManager.getRingtone(getBaseContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
startalarm.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(user_value.length()==0)
{
Toast.makeText(getBaseContext(), "Please enter a value.", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), "alarm set", Toast.LENGTH_LONG).show();
//I want my alarm event to be started from here whenever a new CB sms arrives.
SQLiteDatabase aa = openOrCreateDatabase("MLIdata", MODE_WORLD_READABLE, null);
Cursor c = aa.rawQuery("SELECT CblocationName FROM MLITable WHERE CblocationCode = '"+str+"'", null);
c.moveToFirst();
c.getString(c.getColumnIndex("CblocationName"));
String sas = user_value.getText().toString();
if(sas.equals(c.getString(c.getColumnIndex("CblocationName"))))
{
//here comes the alarm code
if(ringtone == null)
{
Log.d("Debug", "ringtone is null");
}
else
{
ringtone.play();
}
}
}
});
stopalarm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
ringtone.stop();
}
});
}
}
Detailed Explanation : whenever a user enters a new tower location he gets the updated Cell Broadcast message from the tower, so when this cbsms arrives I need to start my event of retrieving the CB area code and compare it with my database of area codes (which obviously have corresponding area code names set by the user) and when there is a match between the user given area name's corresponding area code with my current area code an alarm needs to be started, here I'm not able to do detect the arrival of updated location.
If further explanation is required of my problem statement, please comment.
From the comments received below, I've deduced that I'd need a receiver class, I've created one for my widget which does the same function (Displays the Cb location code on the widget), Now I do not how to activate that in my app.
My WidgetReceiver.java
public class CbReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
String str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB " + msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
abortBroadcast();
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget);
ComponentName thisWidget = new ComponentName(context,MyWidget.class);
remoteViews.setTextViewText(R.id.update,str);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}}
}
Help required.
Thank you.
Start your activity from your receiver on tower change. Use Intents to start your activity from receivers.
Ex: Refer this alarm example for above point, Alarm Example
Register your receiver in Android Manifest.xml.
Send a broadcast message from your receiver class also update your DB inside your receiver.
Catch the same in your activity. You can use Custom Broadcast for this.
Now activate your alarm in activity.
Hope these steps will help you. Refer the example I have mentioned.