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");
Related
I'm new to android development and I'm stuck with the following issue:
I have objects in a listView. When an item in the list is clicked a detailed page with the information appears. This worked fine until at some point the text was displayed only sometimes. When I go back and click on the very same item the text might get displayed correctly again (or not). I have done a textView.getText() and it displays the correct text in the logcat but the user can't actually see this text displayed in the app (at least not always). I wasn't able to pinpoint the mistake and I cannot reproduce the mistake regularly.
FYI: The genre gets displayed always. But title and author only sometimes.
I am grateful for any help! If you have any codestyle/bestpractice remarks please add those to your answers.
Below you can find the relevant code.
Best,
Marc
Activity passing the data
public class BooksActivity extends AppCompatActivity {
private SQLiteDatabase db;
private final BooksDBOpenHelper dbHelper = new BooksDBOpenHelper(this, DBConstants.DB_NAME, null, 1);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_books);
TextView header = this.findViewById(R.id.tv_header);
header.setText(R.string.books_list);
ImageButton backButton = this.findViewById(R.id.toolbar_back_button);
backButton.setOnClickListener(view -> finish());
}
#Override
protected void onStart() {
super.onStart();
db = dbHelper.getWritableDatabase();
ArrayList<CustomBookItem> bookItems = new ArrayList<>();
String table_name = DBConstants.Books.TABLE_NAME;
String[] columns = {
DBConstants.Books.COLUMN_NAME_TITLE,
DBConstants.Books.COLUMN_NAME_AUTHOR,
DBConstants.Books.COLUMN_NAME_GENRE,
DBConstants.Books.COLUMN_NAME_ON_LOAN,
DBConstants.ID
};
String where = null;
String[] where_args = null;
String group_by = null;
String having = null;
String order_by = null;
Cursor cursor = db.query(table_name, columns, where, where_args, group_by, having, order_by);
while (cursor.moveToNext()) {
bookItems.add(new CustomBookItem(
cursor.getString(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)
));
}
cursor.close();
ListView lvMainList = findViewById(R.id.lv_books_list);
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(this, bookItems);
lvMainList.setAdapter(customArrayAdapter);
lvMainList.setOnItemClickListener((adapterView, view, pos, id) -> {
Log.i("BooksActivity", "item was clicked");
CustomBookItem bookItem = (CustomBookItem) adapterView.getAdapter().getItem(pos);
Intent intent = new Intent(this, BookActivity.class);
intent.putExtra(DBConstants.Books.COLUMN_NAME_TITLE, bookItem.getTitle());
intent.putExtra(DBConstants.Books.COLUMN_NAME_AUTHOR, bookItem.getAuthor());
intent.putExtra(DBConstants.Books.COLUMN_NAME_GENRE, bookItem.getGenre());
intent.putExtra(DBConstants.Books.COLUMN_NAME_ON_LOAN, bookItem.getOnLoan());
intent.putExtra(DBConstants.ID, bookItem.getId());
startActivity(intent);
});
customArrayAdapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
db.close();
}
}
Activity receiving the data
public class BookActivity extends AppCompatActivity {
private Resources resources;
private final BooksDBOpenHelper dbHelper = new BooksDBOpenHelper(this, DBConstants.DB_NAME, null, 1);
private SQLiteDatabase db;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_book);
this.resources = this.getResources();
TextView header = this.findViewById(R.id.tv_header);
header.setText(R.string.book);
ImageButton backButton = this.findViewById(R.id.toolbar_back_button);
backButton.setOnClickListener(view -> finish());
}
#Override
protected void onStart() {
super.onStart();
Intent intent = this.getIntent();
String id = intent.getStringExtra(DBConstants.ID);
TextView tvTitle = this.findViewById(R.id.book_title);
tvTitle.setText(intent.getStringExtra(DBConstants.Books.COLUMN_NAME_TITLE));
Log.d("BookActivity", tvTitle.getText().toString());
TextView tvAuthor = this.findViewById(R.id.book_author);
tvAuthor.setText(intent.getStringExtra(DBConstants.Books.COLUMN_NAME_AUTHOR));
Log.d("BookActivity", tvAuthor.getText().toString());
TextView tvGenre = this.findViewById(R.id.book_genre);
tvGenre.setText(intent.getStringExtra(DBConstants.Books.COLUMN_NAME_GENRE));
Log.d("BookActivity", tvGenre.getText().toString());
View loanBookButton = this.findViewById(R.id.loanBookButton);
View returnBookButton = this.findViewById(R.id.returnBookButton);
if (intent.getStringExtra(DBConstants.Books.COLUMN_NAME_ON_LOAN).equals("0")) {
returnBookButton.setBackgroundColor(this.resources.getColor(R.color.grayed_out));
returnBookButton.setEnabled(false);
} else {
loanBookButton.setBackgroundColor(this.resources.getColor(R.color.grayed_out));
loanBookButton.setEnabled(false);
}
loanBookButton.setOnClickListener(view -> loanBook(id));
returnBookButton.setOnClickListener(view -> returnBook(id));
}
public void returnBook(String id) {
this.db = this.dbHelper.getReadableDatabase();
this.db.execSQL("UPDATE " + DBConstants.Books.TABLE_NAME +
" SET " + DBConstants.Books.COLUMN_NAME_ON_LOAN + "='0' " +
"WHERE id=" + id);
this.finish();
}
public void loanBook(String id) {
this.db = this.dbHelper.getReadableDatabase();
this.db.execSQL("UPDATE " + DBConstants.Books.TABLE_NAME +
" SET " + DBConstants.Books.COLUMN_NAME_ON_LOAN + "='1' " +
"WHERE id=" + id);
this.finish();
}
}
Layout of sending activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/container_header_lyt"
layout="#layout/toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"/>
<ListView
android:id="#+id/lv_books_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/container_header_lyt"/>
</RelativeLayout>
Layout of receiving activity
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/container_header_lyt"
layout="#layout/toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/loanBookButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="64dp"
android:layout_marginTop="580dp"
android:layout_marginEnd="229dp"
android:layout_marginBottom="103dp"
android:text="#string/loan_book_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/returnBookButton"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginStart="229dp"
android:layout_marginTop="580dp"
android:layout_marginEnd="64dp"
android:layout_marginBottom="103dp"
android:text="#string/return_book_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/book_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="176dp"
android:layout_marginTop="174dp"
android:layout_marginEnd="176dp"
android:layout_marginBottom="487dp"
android:textAlignment="center"
android:textSize="32sp"
app:layout_constraintBottom_toTopOf="#+id/loanBookButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/book_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="176dp"
android:layout_marginTop="69dp"
android:layout_marginEnd="176dp"
android:layout_marginBottom="399dp"
android:textSize="28sp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/loanBookButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/book_title" />
<TextView
android:id="#+id/book_genre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="176dp"
android:layout_marginTop="69dp"
android:layout_marginEnd="176dp"
android:layout_marginBottom="311dp"
android:textSize="28sp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/loanBookButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/book_author" />
</androidx.constraintlayout.widget.ConstraintLayout>
Edit
I restructured the layout of the receiving activity by changing it from a constraint layout to a relative. I don't know why this worked but it fixed my problem.
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;
for(int i=0;i<j.size();i++)
{
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
JsonObject jb = (JsonObject) j.get(i);
String item = jb.get("item").getAsString();
String unit = jb.get("unit").getAsString();;
String price = jb.get("price").getAsString();;
TableRow tbrow1 = new TableRow(this);
TextView tv01 = new TextView(this);
tv01.setText(item);
tv01.setTextColor(Color.BLACK);
tbrow1.addView(tv01);
TextView tv11 = new TextView(this);
tv11.setText(unit);
tv11.setTextColor(Color.BLACK);
tbrow1.addView(tv11);
TextView tv21 = new TextView(this);
tv21.setText(price);
tv21.setTextColor(Color.BLACK);
tbrow1.addView(tv21);
Button button = new Button(this);
button.setText("+");
button.setTag(item);
tbrow1.addView(button);
final String id_ = (String) button.getTag();
EditText edText = new EditText(this);
edText.setInputType(InputType.TYPE_CLASS_NUMBER);
//edText.setText(0);
tbrow1.addView(edText);
Button button1 = new Button(this);
button1.setText("-");
button.setTag(item);
tbrow1.addView(button1);
final String id1_ = (String) button.getTag();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "button clicked for "+id_, Toast.LENGTH_LONG).show();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "button clicked for "+id1_, Toast.LENGTH_LONG).show();
}
})
}
I'm developing Android app for grocery shop . I'm getting itms details in json
Depending on items number I'm creating dynamic rows.
Now I want to add + and - button in each row .
I want it programmatically
How to to do it.
Example: + - button in zomato while adding food to cart .
As i click + or - button that corresponding item number should increment/decrement
You can use this library. It is a simple Android library to implement a number counter with increment and decrement buttons.
https://github.com/ashik94vc/ElegantNumberButton
try this,
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textViewCount;
int count=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewCount=findViewById(R.id.textViewCount);
textViewCount.setText(""+count);
}
public void itemSubtractClick(View view) {
if (count>0)
textViewCount.setText(""+count--);
else
Toast.makeText(this, "not allowed", Toast.LENGTH_SHORT).show();
}
public void itemAddClick(View view) {
textViewCount.setText(""+count++);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/shape"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:onClick="itemSubtractClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon_subtract" />
<TextView
android:id="#+id/textViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#17F44336"
android:padding="10dp"
android:text="2"
android:textSize="18sp" />
<ImageView
android:onClick="itemAddClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon_add" />
</LinearLayout>
Recently I developed one app. In this, The values are retrieved from the MySQL data base into the spinner. The problem is that it crashes when internet is not present. My intention is, if the internet is not present show default values. Otherwise if the internet is available show the values from MySQL database.
public class MilkProduction extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private EditText quantity;
private Button submit, cancel;
private TextView date_time;
Calendar calander;
SimpleDateFormat simpleDateFormat;
String time;
private AutoCompleteTextView animal_id;
private List<Animal> fruits ;
Boolean isInternetPresent = false;
private ConnectionDetector cd;
private Spinner spinner1;
private String shift_id;
private String product;
String shiftid="",intime="",outtime="";
//JSON Array
private JSONArray result;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private Animal item ;
private Animal animal=new Animal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.milk_production);
animal_id = (AutoCompleteTextView) findViewById(R.id.edt_animal_id);
quantity = (EditText) findViewById(R.id.edt_milkproduction_quan);
date_time = (TextView) findViewById(R.id.txt_timt_date_year);
submit = (Button) findViewById(R.id.btn_prodc_submit);
calander = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
time = simpleDateFormat.format(calander.getTime());
date_time.setText(time);
date_time.setTextSize(15);
students = new ArrayList<String>();
spinner1 = (Spinner) findViewById(R.id.spinner);
spinner1.setOnItemSelectedListener(this);
cd = new ConnectionDetector(getApplicationContext());
//Calling the method that will fetch data
proautocomplete();
prodropdown();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
insertUser();
}
else{
showAlertDialog(MilkProduction.this, "Internet not available",
"Internet is not available in this device", false);
}
}
});
}
private void prodropdown() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser1( new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
String detailsString = Others.getStringFromRetrofitResponse(response);
try {
//Parsing the fetched Json String to JSON Object
JSONObject j = new JSONObject(detailsString);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
private void getStudents(JSONArray j) {
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MilkProduction.this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getShiftid(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
// name = json.getString(Config.TAG_NAME);
name = animal.setShiftid(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getIntime(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
// course = json.getString(Config.TAG_COURSE);
course= animal.setIntime(json.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getOuttime(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
// session = json.getString(Config.TAG_SESSION);
session= animal.setOuttime(json.getString(Config.TAG_SESSION));
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String spin = parent.getItemAtPosition(position).toString();
//Setting the values to textviews for a selected item
shiftid=(getShiftid(position));
intime=(getIntime(position));
outtime=(getOuttime(position));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
shiftid="";
intime="";
outtime="";
}
private void insertUser() {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading","Please wait...",false,false);
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser(
animal_id.getText().toString(),
quantity.getText().toString(),
date_time.getText().toString(),
spinner1.getSelectedItem().toString(),
" ",
shiftid,
intime,
outtime,
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
loading.dismiss();
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MilkProduction.this, output, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
loading.dismiss();
Toast.makeText(MilkProduction.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
}
Layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/mm"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/dairy_layout_height"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:layout_marginTop="25dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:background="#drawable/corner3"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="13dp"
android:layout_gravity="center"
>
<TextView
android:id="#+id/heder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Milk Production"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="5dp"
android:textSize="25sp"
android:textColor="#color/textcolour"
/>
<View
android:layout_width="250dp"
android:layout_height="2dip"
android:background="#023e64"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_shfit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shift : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
android:layout_marginTop="12dp"
/>
<Spinner
android:layout_width="160dp"
android:layout_height="50dp"
android:id="#+id/spinner"
android:layout_gravity="center_horizontal"
android:spinnerMode="dialog"
android:prompt="#string/shift_prompt"
android:background="#android:drawable/btn_dropdown"
android:entries="#array/android_dropdown_arrays1"
style="#android:style/Widget.Holo.Light.Spinner"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Animal : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<AutoCompleteTextView
android:id="#+id/edt_animal_id"
android:layout_width="160dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:layout_alignParentLeft="true"
android:ems="10"
android:text="">
</AutoCompleteTextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_milk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<EditText
android:id="#+id/edt_milkproduction_quan"
android:layout_width="121dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:inputType="number"
android:ems="10"
/>
<TextView
android:id="#+id/txt_milk_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Lts."
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
>
<TextView
android:id="#+id/btn_prodc_submit"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="#dimen/button_sub_txt_size"
android:layout_margin="#dimen/button_layout_margin"
android:background="#drawable/btnbackground"
android:textColor="#color/textcolour"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
I think should try something like that to show the default values if no internet, else get the values of the sql
if(cd.isConnectingToInternet()){
prodropdown();
}else{
//Setting adapter to show the items in the spinner
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("default value 1");
spinnerArray.add("default value 2");
spinnerArray.add("default value 3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
}
I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
XML:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}