Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am a beginner in Android and hoping to achieve text being show when the weather temperature is at various temperatures. For example, if it is 5 degrees, then the text will show the user to "wear a coat".
The code is working fine, but struggling to implement this dynamic text feature. Any help will be greatly appreciated!
Java Code:
public class AdviseMe extends Activity {
private TextView cityText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView textview1;
private TextView hum;
private ImageView imgView;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.adviseme);
String city = "London,UK";
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params)
Weather weather = new Weather();
String data = ( (new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
weather.iconData = ( (new
WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0,
weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + ", " + weather.location.getCountry());
condDescr.setText(weather.currentCondition.getCondition() + "
weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "C");
hum.setText(": " + weather.currentCondition.getHumidity() + "%");
press.setText(": " + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText(": " + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "");
}
}
}
The XML Code:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:src="#drawable/cleanbackground" />
<TextView
android:id="#+id/cityText"
style="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/condIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/cityText" />
<TextView
android:id="#+id/condDescr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/condIcon"
android:layout_alignLeft="#id/condIcon"
/>
<TextView
android:id="#+id/temp"
style="#style/tempStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_alignBaseline="#id/condDescr"
android:layout_toRightOf="#id/condDescr"/>
<TextView
android:id="#+id/pressLab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/condDescr"
android:text="Pressure"
android:layout_marginTop="15dp" />
<TextView
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/pressLab"
android:layout_toRightOf="#id/pressLab"
style="#style/valData"/>
<TextView
android:id="#+id/humLab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/pressLab"
android:text="Humidity" />
<TextView
android:id="#+id/hum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/humLab"
android:layout_toRightOf="#id/humLab"
android:layout_marginLeft="4dp"
style="#style/valData"/>
<TextView
android:id="#+id/windLab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/humLab"
android:text="Wind" />
<TextView
android:id="#+id/windSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/windLab"
android:layout_toRightOf="#id/windLab"
android:layout_marginLeft="4dp"
style="#style/valData" />
<TextView
android:id="#+id/windDeg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/windLab"
android:layout_toRightOf="#id/windSpeed"
android:layout_marginLeft="4dp"
style="#style/valData"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="124dp"
android:text="TextView" />
You need to implement a handler, which will check the Temperature variable every five seconds, based on the degrees will display a custom message in your textview. There is one more efficient method of doing this using a local broadcast
An Example of Handler would be:
public void functionA(){
//fetch value from source.
//update value to text view
//update custom textview
}
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
// Do your task here.
//Call functionA() here.
}timerHandler.postDelayed(this, 5000);
}
};
Start your handler like:
timerHandler.postDelayed(timerRunnable, 0);
Stop it like:
timerHandler.removeCallbacksAndMessages(null);
Method two use a local broadcast (More robust, less CPU consuming):
ReceiverActivity.java
An activity that watches for notifications for the event named "custom-event-name".
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
SenderActivity.java
The second activity that sends/broadcasts notifications.
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Every time a button is clicked, we want to broadcast a notification.
findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
With the code above, every time the button R.id.button_send is clicked, an Intent is broadcasted and is received by mMessageReceiver in ReceiverActivity.
The debug output should look like this:
01-16 10:35:42.413: D/sender(356): Broadcasting message
01-16 10:35:42.421: D/receiver(356): Got message: This is my message!
A dirty way of achieving what you want is:
public void functionA(){
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
}
At your class level code the handler like:
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
functionA()
}timerHandler.postDelayed(this, 5000);
}
};
From your onCreate start it like(Anywhere in onCreate):
timerHandler.postDelayed(timerRunnable, 0);
Related
I am using a progress bar sample from Github however I noticed that the progress bar fill is set to a fixed value. For example, if the step count goal is 10 (.java class) the man should be "10" in the .XML
My goal: when the user inputs their goal step count, the "10" should be variable and change depending on user input.
java snippet:
ProgressBar progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", lastStep, stepCounter); //animate only from last known step to current step count
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
lastStep = stepCounter;
XML snippet
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="376dp"
android:layout_height="392dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="10"
android:progress="0"
android:progressDrawable="#drawable/circular" />
EDIT********************EDIT
Sorry maybe my question wasn't clear. To provide an example...if the users step goal is 500. I need the progress bar to fill respectively. Therefore, IF step_count = 250 then progress bar should be half full, IF step_count = 750 then should be 3/4 full. I need the progression to be respective to a variable value.
Set android:indeterminate="false". See this fully implemented code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:minHeight="50dp"
android:minWidth="200dp"
android:max="100"
android:indeterminate="false"
android:progress="0" />
<TextView
android:id="#+id/tView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/pBar"
android:layout_below="#+id/pBar" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Start Progress"
android:layout_below="#+id/tView"/>
public class MainActivity extends AppCompatActivity {
private ProgressBar pgsBar;
private int i = 0;
private TextView txtView;
private Handler hdlr = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pgsBar = (ProgressBar) findViewById(R.id.pBar);
txtView = (TextView) findViewById(R.id.tView);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = pgsBar.getProgress();
new Thread(new Runnable() {
public void run() {
while (i < 100) {
i += 1;
// Update the progress bar and display the current value in text view
hdlr.post(new Runnable() {
public void run() {
pgsBar.setProgress(i);
txtView.setText(i+"/"+pgsBar.getMax());
}
});
try {
// Sleep for 100 milliseconds to show the progress slowly.
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}
I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.
public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" + "(?=.*[0-9])" +
"(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[##$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");
public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;
public String Mess = null;
public String jmeno, prijmeni, email, heslo, heslo2;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_registrace);
TextView login = (TextView) findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(this);
editJmeno = (EditText) findViewById(R.id.txtJmeno);
jmeno = editJmeno.getText().toString().trim();
editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
prijmeni = editPrijmeni.getEditableText().toString().trim();
editEmail = (EditText) findViewById(R.id.txtEmail);
email = editEmail.getEditableText().toString().trim();
editPwd = (EditText) findViewById(R.id.txtPassword);
heslo = editPwd.getEditableText().toString().trim();
editPwd2 = (EditText) findViewById(R.id.txtPassword2);
heslo2 = editPwd2.getEditableText().toString().trim();
btn = (Button) findViewById(R.id.btnRegistrace);
btn.setOnClickListener(this);
}
public boolean validujPrijmeni() {
if(prijmeni.isEmpty()) {
Mess = "Příjmení" + "\n";
return false;
} else {
return true;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lnkLogin:
Intent intent = new Intent(Registrace.this, Login.class);
startActivity(intent);
break;
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!prijmeni.isEmpty()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.
Here is layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<TextView
android:id="#+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Registrace"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="15dp"
android:text="Příjmení" />
<EditText
android:id="#+id/txtPrijmeni"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="#+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="15dp"
android:text="Jméno"/>
<EditText
android:id="#+id/txtJmeno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="#+id/thirdTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="#+id/fourTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heslo"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<TextView
android:id="#+id/fiveTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heslo, znova pro kontrolu"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtPassword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<Button
android:id="#+id/btnRegistrace"
android:onClick="Registrace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Registrovat" />
<TextView android:id="#+id/lnkLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Jste již registrován?? Přihlaste se zde."
android:gravity="center"
android:textSize="20dp"
android:textColor="#3F51B5"
android:onClick="test"/>
Do this: prijmeni = editPrijmeni.getEditableText().toString().trim(); in the onClick() method.
You are doing it at the creation of the Activity so the EditText control is empty. It won't automatically update the prijmeni string on change.
Here is how your code could look like with some small improvements.
It could also be further refined but it seems you just begin so it's already fine.
public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" + "(?=.*[0-9])" +
"(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[##$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");
private EditText editPrijmeni;
private EditText editJmeno;
private EditText editEmail;
private EditText editPwd;
private EditText editPwd2;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_registrace);
// Shouldn't you use a button instead of a text view?
// It seems you want a "Login" button to go to a LoginActivity
final TextView login = (TextView) findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(this);
// You could use https://jakewharton.github.io/butterknife which simplifies this boilerplate code a lot
editJmeno = (EditText) findViewById(R.id.txtJmeno);
editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
editEmail = (EditText) findViewById(R.id.txtEmail);
editPwd = (EditText) findViewById(R.id.txtPassword);
editPwd2 = (EditText) findViewById(R.id.txtPassword2);
btn = (Button) findViewById(R.id.btnRegistrace);
btn.setOnClickListener(this);
}
public boolean validujPrijmeni() {
// if 'Mess' was for a validation message don't set it in the validation method.
// define a string in your resources.
// show/hide a TextView with that message from where you use the validation method.
final String prijmeni = editPrijmeni.getEditableText().toString().trim();
return !prijmeni.isEmpty();
}
// I would not declare the activity as a OnClickListener but use anonymous classes in the onCreate method
// calling method on this class.
// or if you use ButterKnife you can do so with OnClick annotations.
// This is to prevent the use of switch which is not great code.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lnkLogin:
Intent intent = new Intent(Registrace.this, Login.class);
startActivity(intent);
break;
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
final String prijmeni = editPrijmeni.getEditableText().toString().trim();
if (this.validujPrijmeni()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
you are getting values from edittext in on create.it's actually wrong cause in that time those edittexts are empty.the correct action is to get text from edittext in on click of register button
before
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!prijmeni.isEmpty()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
after
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!editJmeno.getText().toString().isEmpty()) {
Toast.makeText(this, editJmeno.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
I am developing an signup activity in android app. I want show the country telephone code(get the country from device). It may show the list of countries containing with flag, country telephone code, country name. I get the code of country code picker from https://github.com/mukeshsolanki/country-picker-android . It contain the complete code. I want to set the default country is in the phone.
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+country);
When i using this code i get the country code "in". But i want to display telephone code and flag, name. When i open the screen. I want to display it automatically.
My code is shown below
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView
android:background="#drawable/logo"
android:layout_gravity="center_horizontal"
android:layout_width="150dp"
android:layout_height="150dp" />
<Button
android:text="Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonCountry" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="#d11f08"
android:entries="#array/android_dropdown_arrays"
android:padding="5dp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="44dp"
android:inputType="phone"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"/>
</LinearLayout>
</ScrollView>
Main.Activity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
Button buttonCountry;
private Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editTextPhone);
button = (Button) findViewById(R.id.buttonSubmit);
buttonCountry = (Button) findViewById(R.id.buttonCountry);
spinner1 = (Spinner) findViewById(R.id.spinner1);
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+countryCodeValue);
//String mPhoneNumber = tm.getLine1Number(); //not getting phone number
//System.out.println("phone no = "+mPhoneNumber);
buttonCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
final CountryPicker picker = CountryPicker.newInstance("Select Country");
picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
picker.setListener(new CountryPickerListener() {
#Override
public void onSelectCountry(String name, String code, String dialCode, int flagDrawableResID) {
// Implement your code here
Log.d("LOGTAG", "output1 : name = "+name+" code = "+code+" dialcode = "+dialCode+" flag = "+flagDrawableResID);
picker.dismiss();
}
});
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
// Todo when item is selected by the user
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
Reference : https://github.com/hbb20/CountryCodePickerProject
try to get country code using Lat, long
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1); // lati : Latitude ,longi : Longitude
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
code=addressList.get(0).getCountryCode();
System.out.println("code :: "+addressList.get(0).getCountryCode());
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
String locale = context.getResources().getConfiguration().locale.getCountry();
You can use this library
Click here
by then you can do this
new DialogPlusBuilder().blurBackground()
.buildCountriesListDialog(true,new DialogPlus.CountriesDialogListener() {
#Override
public void onItemClicked(CountryDataModel countryDataModel, DialogPlus dialogPlus) {
super.onItemClicked(countryDataModel, dialogPlus);
Toast.makeText(MainActivity.this,countryDataModel.getName()+ countryDataModel.getPhone_code(), Toast.LENGTH_SHORT).show();
}
})
.show(this.getSupportFragmentManager(), "Countries List Dialog");
How to update my UI button for disabled button on/off if i have condition. The condition : if i get value = 1.0 the button power on is disabled & and if i get value 0 the button power off disabled. I want the button always show up the new value.
This is my code :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_controller, container, false);
mSwitchStatus = (TextView) rootView.findViewById(R.id.statusSwitch);
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
ImageButton Off = (ImageButton)rootView.findViewById(R.id.off);
callAsynchronousTask();
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "ON", Toast.LENGTH_SHORT).show();
SendApi sendApi = new SendApi();
sendApi.execute();
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "OFF", Toast.LENGTH_SHORT).show();
SendApi sendApi = new SendApi();
sendApi.execute();
}
});
// Inflate the layout for this fragment
return rootView;
}
Repeat AsyncTask
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
GetApi getApi = new GetApi();
getApi.execute();
} catch (Exception e) {
android.util.Log.i("Error", "Error");
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 100);
}
AsyncTask for GETApi
public class GetApi extends AsyncTask<Object, Object, Value[]> {
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private ImageButton On,Off ;
#Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
String status = Double.toString(variableValues[0].getValue());
mSwitchStatus.setText(status);
if(status.equals("1.0")){
On.setVisibility(View.INVISIBLE);
}
}
}
Fragment_controller.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#1d4851"
tools:context=".activity.ControllerFragment">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/off"
android:src="#drawable/ic_off"
android:background="#null"
android:layout_marginTop="79dp"
android:layout_below="#+id/textView2"
android:layout_alignLeft="#+id/on"
android:layout_alignStart="#+id/on"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/on"
android:background="#null"
android:src="#drawable/ic_on"
android:layout_marginTop="87dp"
android:layout_alignTop="#+id/off"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Water Pump Controller "
android:id="#+id/textView2"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginTop="19dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" "
android:id="#+id/statusSwitch"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginTop="250dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
you have initialize your button in onCreateView like
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
and trying to access it in onPostExecute().they aren't global.
And to disable you have to call setEnable(false) not setVisibility
And you can also send it as Rathna Kumaran said.
public class GetApi extends AsyncTask<Object, Object, Value[]> {
private Button button;
public GetApi(Button mButton){
this.button = button;
}
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxx";
#Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
String status = Double.toString(variableValues[0].getValue());
mSwitchStatus.setText(status);
if(status.equals("1.0")){
button.setVisibility(View.INVISIBLE);
}
}
}
1.Create a constructor in a AsyncTask and send the button as parameter. ex. getApi(buttonOne).execute();
Inside a getApi() constructor declare a local variable "Button" and assigned to that.
In onPostExecute() -> buttonOne.setVisibility(View.INVISIBLE).
In asyncTask , "onPostExecute()" will perform in a main thread. UI elements should only get update in a main thread. So that passing a UI element into an Asynctask and it can be update inside the onPostExecute.
I am developing an application using sms, my requirement is 1) send sms with static values 2)whenever we click on edit button we can change values and send sms , I can do both of them successfully but my third requirement is to send sms only when click on edit and change values click on submit buttons, without change value I do not want send sms. I want when click on edit button then only send sms, i tried with if(editBtn.isSelected) but it is not working. please tell any solution
my code is
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical" >
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editBtn"
android:text="EDIT"
android:textColor="#00FF00"
android:onClick="editListener"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NUMBER"
android:textSize="20dip"/>
<EditText android:layout_width="150dip"
android:layout_height="wrap_content"
android:id="#+id/numberEdit"
android:text="8989897979"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MESSAGE"
android:textSize="20dip"/>
<EditText android:layout_width="150dip"
android:layout_height="wrap_content"
android:id="#+id/messageEdit"
android:text="HAI HOW R U"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/subBtn"
android:text="SUBMIT"/>
</LinearLayout>
Activty
public class MainActivity extends Activity {
private EditText contactEdit;
private EditText messageEdit;
private Button submitBtn;
private Button editBtn;
String contact;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactEdit = (EditText)findViewById(R.id.numberEdit);
messageEdit = (EditText)findViewById(R.id.messageEdit);
submitBtn = (Button)findViewById(R.id.subBtn);
editBtn = (Button)findViewById(R.id.editBtn);
if(editBtn.isSelected()){
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contact = contactEdit.getText().toString();
message = messageEdit.getText().toString();
try{
SmsManager manger = SmsManager.getDefault();
manger.sendTextMessage(contact, null, message, null,
null);
Toast.makeText(getApplicationContext(), "SMS SENT",
100).show();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "SMS NOT
SEND", 100).show();
e.printStackTrace();
}
}
});
}
else {
Toast.makeText(getApplicationContext(), "NOT EDITED", 100).show();
}
editBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
changeEdit();
}
});
}
private void changeEdit(){
contactEdit.setClickable(true);
contactEdit.setCursorVisible(true);
contactEdit.setFocusable(true);
contactEdit.setFocusableInTouchMode(true);
messageEdit.setClickable(true);
messageEdit.setCursorVisible(true);
messageEdit.setFocusable(true);
messageEdit.setFocusableInTouchMode(true);
}
}
Try to use OnTouchListener for the edittext
sample,
editBtn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
changeEdit();
return true;
}
});
if its not working
Create a boolean variable Globally and make it true if u touched onto the edittext,
//In grobal
boolean e_clicked = false;
//Inside the Edittext onTouchListener
e_clicked=true;
and check
if(e_clicked)
{
// your sms send action
}
try this
public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent=new Intent(context,Service.class);
//get lat/lng and pass it or get from service if u want
intent.putExtra("lat","lat");
intent.putExtra("lon","lng");
context.startService(intent);
}
}
public void SetAlarm(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 10);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
calendar.getTimeInMillis(), pi);
}