EditText is being a end of year nightmare, and I when finding view by ID, seem to be returned with null when getting text from it.
Settings Activity:
public class Settings extends ActionBarActivity {
String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
createPreferences();
}
public void createPreferences(){
SharedPreferences settings = getSharedPreferences("emailAddress", 0);
getData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
public void getData(){
email = getEmail();
}
public String getEmail(){
setContentView(R.layout.activity_settings);
EditText usernameEditText = (EditText)findViewById(R.id.email_address);
String Username = usernameEditText.getText().toString();
if (Username.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return Username;
}
System.out.println(email + " 8888888888888888888");
if(Username !=null){
email = Username;
}
if (email==null){
SharedPreferences setting = getSharedPreferences("emailAddress", Context.MODE_PRIVATE);
//check preferences.
String emailNew = setting.getString("emailAddress", "n").toString();
if(emailNew != null){
email = emailNew;
}
if(email==null){
//shit
}
}
if(email!= null){
}
return email;
}
}
Settings 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: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="com.example.keepsafe.Settings" >
<EditText
android:id="#+id/email_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/enteremail"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/password_enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/email_address"
android:layout_alignRight="#+id/email_address"
android:layout_below="#+id/email_address"
android:layout_marginTop="33dp"
android:ems="10"
android:hint="Enter password"
android:inputType="textPassword" />
<EditText
android:id="#+id/email_address_toSendto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/enteremail"
android:inputType="textEmailAddress"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password_enter"
android:layout_below="#+id/password_enter"
android:layout_marginLeft="14dp"
android:layout_marginTop="29dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/SettingsSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password_enter"
android:layout_alignRight="#+id/password_enter"
android:layout_centerVertical="true"
android:onClick="dataSubmit"
android:text="Submit" />
</RelativeLayout>
I have no idea, and I have been battling this with google for a few hours.
Any help is appreciated, I'm new to this.
Follow the step as mentioned below :
Don't use the setContentView() method inside your getEmail() method.
So the code after the above edits would look as below :
public class Settings extends ActionBarActivity {
String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
createPreferences();
}
public void createPreferences(){
SharedPreferences settings = getSharedPreferences("emailAddress", 0);
getData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
public void getData(){
email = getEmail();
}
public String getEmail(){
//Removed setContentView() from this method
EditText usernameEditText = (EditText)findViewById(R.id.email_address);
String Username = usernameEditText.getText().toString();
if (Username.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return Username;
}
System.out.println(email + " 8888888888888888888");
if(Username !=null){
email = Username;
}
if (email==null){
SharedPreferences setting = getSharedPreferences("emailAddress", Context.MODE_PRIVATE);
//check preferences.
String emailNew = setting.getString("emailAddress", "n").toString();
if(emailNew != null){
email = emailNew;
}
if(email==null){
//shit
}
}
if(email!= null){
}
return email;
}
}
Just a Suggestion : Reference your Views in JAVA after setContentView in your onCreate() method and declare them globally in case you want to access them in many functions.
Hope this Helps!
Related
I have problems in Android Studio, I don't know how to import the switch ID generically, so I can call this function from all the switches.
I tried to put a description of the switch with the number of it so I can get a number like "1".
public class MainActivity extends AppCompatActivity {
Switch switch1, switch2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = findViewById(R.id.switch1);
switch2 = findViewById(R.id.switch2);
}
public void OnClick(View view) {
String stateSwitch = "";
if(switch1.isChecked() == false){
stateSwitch = "0";
} else {
stateSwitch = "1";
}
if(switch2.isChecked() == false){
stateSwitch = "0";
} else {
stateSwitch = "1";
}
String idSwitch = switch1.getContentDescription().toString();
// What can I put instead of "switch1" or "switch2" to select the switch generically?
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute("switch", stateSwitch, idSwitch);
}
}
XML of the switches
<Switch
android:id="#+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="2"
android:onClick="OnClick"
android:text="switch2" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="1"
android:onClick="OnClick"
android:text="switch1" />
Sorry for my english.
To get an ID of widget in a code simply get view.getId() it will return a positive integer used to identify the view,
to get id generically you can call
String mId = Integer.toString(view.getId());
when you click on switch1 it will return the id of switch1 similarly when you click on switch2 it will return the id of switch2.
Use checked changed listener and get the id there. For example:
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="152dp"
android:text="Switch1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Switch
android:id="#+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Switch2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/switch1" />
//////////Java Code///////////
public class MainActivity extends AppCompatActivity {
Switch gSwitch,switch1, switch2;
boolean state;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = findViewById(R.id.switch1);
switch1 = findViewById(R.id.switch2);
switch1.setOnCheckedChangeListener(checkedChangeListener);
switch2.setOnCheckedChangeListener(checkedChangeListener);
}
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
id = buttonView.getId();
gSwitch = findViewById(id);// generic switch;
state = isChecked;
// call your method here for example:
// BackgroundWorker backgroundWorker = new BackgroundWorker(this);
// backgroundWorker.execute("switch", state, id);
}
};
}
Use View Binding
For each module that uses view binding, set the viewBinding build option to true in the module-level build.gradle file:
buildFeatures {
dataBinding = true
}
And Remove all imports from kotlinx.android.synthetic.
See more here
i'm having problems trying to add 2 buttons into my listview, i'm uploading a picture with what i have and what i want
So, i just want to add those 2 buttons there, but i've been trying to do it using custom adapters but i still can't do it, if anyone could help me i would really appreciate it.
My files so far:
activity_vendor_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/activity_vendedor_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:src="#drawable/logo"
android:layout_width="209dp"
android:layout_height="106dp"
android:layout_marginBottom="20dp"
android:layout_gravity="center_horizontal" />
/>
<ImageView
android:src="#drawable/orderid1"
android:layout_width="134dp"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
/>
<SearchView
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/seacrhBar"
android:textColor="#color/colorVendor"
android:layout_marginTop="25dp"
android:background="#drawable/vendor_bars_background"/>
<android.support.v7.widget.AppCompatButton
android:text="AGREGAR ORDEN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="8dp"
android:textStyle="bold"
android:textColor="#color/colorVendor"
android:background="#drawable/single_button"
android:id="#+id/add_order1"
android:onClick="EVENTO" />
<ListView
android:layout_width="wrap_content"
android:layout_height="190dp"
android:id="#+id/tablaPedidos"
android:choiceMode="singleChoice"
android:layout_above="#+id/editText2"
android:background="#drawable/vendor_bars_background"
android:layout_weight="0.13" />
<android.support.v7.widget.AppCompatButton
android:text="CERRAR SESIÓN"
android:layout_width="120sp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="135dp"
android:textStyle="bold"
android:textColor="#color/colorVendor"
android:background="#drawable/button_login_form"
android:id="#+id/signOut2_order_form"
android:onClick="logout" />
</LinearLayout>
MainActivity.java
public class LoginActivity extends AppCompatActivity {
GlobalClass appContext;
#BindView(R.id.input_username)
EditText _usernameText;
#BindView(R.id.input_password)
EditText _passwordText;
#BindView(R.id.btn_login)
Button _loginButton;
ProgressDialog progressDialog;
//Invocación de servicio para acceso al API
UsersHandler client = ServiceGenerator.createService(UsersHandler.class);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ButterKnife.bind(this);
appContext = (GlobalClass)getApplicationContext();
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBackPressed() {
moveTaskToBack(false);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public void login() {
if (!validate()) {
// onLoginFailed("Login failed");
return;
}
_loginButton.setEnabled(false);
progressDialog = new ProgressDialog(LoginActivity.this,R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Autenticando...");
progressDialog.show();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
onLoginSuccess();
//progressDialog.dismiss();
}
}, 3000);
progressDialog.dismiss();
String userType = appContext.getSessionUserType();
loadUserView(userType);
}
public boolean validate() {
boolean valid = true;
String username = _usernameText.getText().toString().trim();
String password = _passwordText.getText().toString();
//if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
if (username.isEmpty()) {
_usernameText.setError("Ingrese un usuario válido.");
valid = false;
} else {
_usernameText.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
_passwordText.setError("No menos de 4 caracteres alfanuméricos");
valid = false;
} else {
_passwordText.setError(null);
}
if (valid) {
valid = validateApi(1, username, password);
}
return valid;
}
public boolean validateApi(int i, String username, String password) {
appContext.setSessionToken("1");
appContext.setSessionUserType(Constants.COURIER);
if (username.equals("v"))
appContext.setSessionUserType(Constants.VENDOR);
appContext.setSessionUsername("tester");
appContext.setSessionCompany("test");
appContext.saveSessionAttributes();
return true;
}
public boolean validateApi(String username, String password) {
boolean valid = false;
//Creación de request
UserLoginRequest requestObj = new UserLoginRequest(username, password);
//Declaración de request
Call<ResponseBody> call = client.userLogin(requestObj);
JSONObject json = null;
try {
ResponseBody responseBody = call.execute().body();
json = UtilsController.getJsonResponse(responseBody);
boolean success = UtilsController.isJsonValid(json);
String error = UtilsController.extractMessage(json);
if (success) {
User response = (User) UtilsController.extractDataJson(json, User.class);
appContext.setSessionToken(response.getToken());
appContext.setSessionUserType(response.getUserType());
appContext.setSessionUsername(response.getUsername());
appContext.setSessionCompany(response.getCompanyName());
appContext.saveSessionAttributes();
valid = true;
} else {
onLoginFailed(error);
return false;
}
} catch (IOException e) {
//Error en lectura de respuesta de servidor
onLoginFailed("Error interno. Intente más tarde");
} catch (JSONException e) {
//Error en campos de respuesta
onLoginFailed("Error interno. Intente más tarde");
} catch (Exception e) {
//Error general
if (json == null) {
onLoginFailed("Error interno. Intente más tarde");
}
onLoginFailed("Login failed");
}
return valid;
}
public void loadUserView(String userType) {
if (userType != null && Constants.VENDOR.equals(userType)) {
Intent userView = new Intent(this, VendorMain.class);
startActivity(userView);
} else if (Constants.COURIER.equals(userType)) {
Intent userView = new Intent(this, CourierMain.class);
startActivity(userView);
}
}
}
row_item.xml (Picture Below)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
</LinearLayout>
<Button
android:text="EDITAR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/cancel_btn" />
<Button
android:text="Cancelar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edit_btn"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/cancel_btn"
android:layout_toStartOf="#+id/cancel_btn"
android:layout_marginRight="7dp"
android:layout_marginEnd="7dp" />
<TextView
android:id="#+id/orden_title_text"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ORDEN #"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:layout_alignBaseline="#+id/edit_btn"
android:layout_alignBottom="#+id/edit_btn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/textbox1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:text=" "
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:layout_alignBaseline="#+id/orden_title_text"
android:layout_alignBottom="#+id/orden_title_text"
android:layout_toRightOf="#+id/orden_title_text"
android:layout_marginStart="7dp" />
</RelativeLayout>
row_item.xml "What i have so far"
If another files is needed in order to help me, let me know and i'll upload it.
Thanks you so much guys.
create a class like
public class TestAdapter extends BaseAdapter {
Context context;
public TestAdapter(Context context)
{
this.context=context;
}
//count of number of items in listview may be depending on the array ua passing....here i am keeping 5 it may be according to you!
int count=5;
#Override
public int getCount() {
return 5;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= LayoutInflater.from(context).inflate(R.layout.row_item,parent,false);
TextView ordentitle=(TextView)convertView.findViewById(R.id.orden_title_text);
TextView textbox1=(TextView)convertView.findViewById(R.id.textbox1);
ordentitle.setText("Whatever yout text is");
textbox1.setText("whatever your text is");
Button editar=(Button)convertView.findViewById(R.id.edit_btn);
Button cancel=(Button)convertView.findViewById(R.id.cancel_btn);
editar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//funtionality of edit button
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//functionality of cancel button
}
});
return convertView;
}
}
and then set this adapter to your listview in activity or fragment like this:
TestAdapter testAdapter=new TestAdapter(YourActivity.this)
yourlistview.setAdapter(testAdapter);
one more pointer :
YOU GAVE EDIT BUTTON id as cancel_btn and CANCEL BUTTON id as edit_btn!
You could create a new class that extends BaseAdapter and in the getView method you do w/e you want with the buttons. In the the activity with the listView you use the setAdapter.
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");
I am working in android studio with GSON and Retrofit 1, which is stable. I am in need to find out why non of the information is showing, the GSON should be putting the JSON information in the model class of getters/setters. I am making a Movie App using the imdb api, I can share my code here if you would like to review the project as a whole, but otherwise below is some of the code:
GitHub Project
This is the detail item xml I am trying to populate then put in the list in the 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"
android:paddingRight="0dp"
android:paddingBottom="0dp"
android:paddingTop="0dp"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.evanglazer.moviezone.MainActivity"
android:id="#+id/top">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="#+id/movieView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="IMDB Rating:"
android:id="#+id/imdbText"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/movieView"
android:layout_toEndOf="#+id/movieView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/imdbRatingText"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imdbText"
android:layout_toEndOf="#+id/imdbText"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="UserBase Vote:"
android:id="#+id/userText"
android:padding="10dp"
android:layout_centerInParent="#+id/imdbText"
android:layout_below="#+id/imdbText"
android:layout_alignRight="#+id/releaseDateText"
android:layout_alignEnd="#+id/releaseDateText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/userRatingText"
android:padding="10dp"
android:layout_below="#+id/imdbText"
android:layout_toRightOf="#+id/imdbText"
android:layout_toEndOf="#+id/imdbText"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Release Date:"
android:id="#+id/releaseText"
android:padding="10dp"
android:layout_below="#+id/userText"
android:layout_toLeftOf="#+id/userRatingText"
android:layout_toStartOf="#+id/userRatingText"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/releaseDateText"
android:layout_below="#+id/releaseText"
android:layout_alignRight="#+id/releaseText"
android:layout_alignEnd="#+id/releaseText" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/middle">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trailer 1"
android:id="#+id/trailer1"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trailer 2"
android:id="#+id/trailer2"
android:layout_below="#+id/trailer1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="100dp"
android:id="#+id/editText"
android:layout_below="#+id/trailer2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
Here is the detail main:
<?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:id="#+id/main2"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true">
</ListView>
</RelativeLayout>
Here is the detail activity:
public class DetailActivity extends ListActivity{
public static final String URL_IMAGE_ENDPOINT = "http://image.tmdb.org";
public static final String URL_API_ENDPOINT = "http://api.themoviedb.org";
FragmentManager fm = getFragmentManager();
List<MovieDetail> details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_main);
//fm.beginTransaction().replace(R.id.main2, new Detail()).commit();
//fm.beginTransaction().replace(R.id.main2, new NavBar()).commit();
if (isOnline()) {
requestData();
} else {
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData()
{
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(URL_API_ENDPOINT)
.build();
MovieAPI api = adapter.create(MovieAPI.class);
api.getMovieDetails(new Callback<List<MovieDetail>>() {
#Override
public void success(List<MovieDetail> movieDetails, Response response) {
details = movieDetails;
// update display
updateDisplay();
}
#Override
public void failure(RetrofitError arg0) {
// TODO Auto-generated method stub
}
});
}
protected void updateDisplay() {
//Use FlowerAdapter to display data
MovieDetailAdapter adapter = new MovieDetailAdapter(this, R.layout.movie_detail_fragment, details);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this,SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is how I am api through retrofit:
public interface MovieAPI {
#GET("/3/movie/273248?api_key=ea8f68dc2c7b43a3df248b9a638f5fb4")
void getMovieDetails(Callback<List<MovieDetail>> callback);
#GET("3/movie/5493/movie/549")
void getPopularMovies(Callback<List<MovieDetail>> response);
}
Here is the model for the objects I am trying to read in from the callback:
public class MovieDetail {
private String poster_path;
private String release_date;
private int id;
private String original_title;
private double vote_average;
private int gridPos;
private Bitmap bitmap;
public int getGridPos() {
return gridPos;
}
public void setGridPos(int gridPos) {
this.gridPos = gridPos;
}
public String getPoster_path() {
return poster_path;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOriginal_title() {
return original_title;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public double getVote_average() {
return vote_average;
}
public void setVote_average(double vote_average) {
this.vote_average = vote_average;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
I am trying to create a demo app where the users enter a search and destination, the data will be queried from parse.com and then the matching result will be displayed in the next screen's listview. I have followed a few tutorials but for sure haven't been able to grasp the concept concretely enough. When I enter a search query, the progress bar shows up and then the application goes back into the previous activity. I can't understand where exactly things are going wrong.
This is my mainactivity class.
public class CarpoolingActivitySearch extends ActionBarActivity {
ListView listView;
ArrayList<Travellers> travellers;
CarpoolingAdapter adapter;
protected ProgressDialog proDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_carpooling_activity_search);
final EditText mSrc = (EditText)findViewById(R.id.carpooling_source);
final EditText mDst = (EditText)findViewById(R.id.destination);
Button mSubmitButton = (Button)findViewById(R.id.carpooling_submit);
mSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String source = mSrc.getEditableText().toString();
String destination = mDst.getEditableText().toString();
listView = (ListView) findViewById(R.id.list);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Carpooling");
query.whereEqualTo("Source", source); //assume you have a DonAcc column in your Country table
query.whereEqualTo("Destination", destination); //assume you have a DonAcc column in your Country table
startLoading();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if(e==null)
{
for(int i=0;i<parseObjects.size();i++)
{
Travellers travellers1 = new Travellers();
travellers1.setSource("Source");
travellers1.setDestination("Destination");
travellers.add(travellers1);
if(travellers.size() > 0)
{
adapter = new CarpoolingAdapter(getApplicationContext(),R.layout.activity_carpooling_activity_search,travellers);
listView.setAdapter(adapter);
} else {
AlertDialog.Builder popup = new AlertDialog.Builder(CarpoolingActivitySearch.this);
popup.setMessage("Seems our servers are busy. Try again in some time.");
popup.setPositiveButton("Back",null);
AlertDialog dialog = popup.create();
dialog.show();
}
}
stopLoading();
finish();
}
else {
stopLoading();
AlertDialog.Builder popup = new AlertDialog.Builder(CarpoolingActivitySearch.this);
popup.setMessage(e.getMessage());
popup.setPositiveButton("Back",null);
AlertDialog dialog = popup.create();
dialog.show();
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_carpooling_activity_search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void startLoading() {
proDialog = new ProgressDialog(this);
proDialog.setMessage("loading...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setCancelable(false);
proDialog.show();
}
protected void stopLoading() {
proDialog.dismiss();
proDialog = null;
}
}
I have created a custom adapter for this purpose.
public class CarpoolingAdapter extends ArrayAdapter<Travellers> {
ArrayList<Travellers> travellersArrayList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
Context context;
public CarpoolingAdapter(Context context, int resource, ArrayList<Travellers> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
travellersArrayList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null) {
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.mSource = (TextView)convertView.findViewById(R.id.textView);
holder.mDestination = (TextView)convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.mSource.setText(travellersArrayList.get(position).getSource());
holder.mDestination.setText(travellersArrayList.get(position).getDestination());
return convertView;
}
static class ViewHolder {
public TextView mSource;
public TextView mDestination;
}
}
And the travellers class with a default constructor and getter/setter methods.
public class Travellers {
private String Source;
private String Destination;
public Travellers() {
}
public Travellers(String source, String destination) {
super();
Source = source;
Destination = destination;
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public void setDestination(String destination) {
Destination = destination;
}
}
The main layout file named activity_carpooling_activity_search.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.example.android.myapplication.Carpooling.Carpooling">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/carpooling_source"
android:hint="Source"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/destination"
android:hint="Destination"
android:layout_below="#+id/carpooling_source"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="86dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/carpooling_submit"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_toEndOf="#+id/carpooling_submit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_below="#+id/carpooling_submit">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</ScrollView>
</RelativeLayout>
And finally my list_item_deatil.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="174dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_weight="0.13" />
<TextView
android:layout_width="245dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_weight="0.13" />
</LinearLayout>
What should I modify to make it work appropriately? I am not getting any errors as such.
First of all, you have posted a very long code blocks where indentation is not good enough to read you code.
So what I understood, as your ParseException e is null that means there is no exception. Inside that if block, after the for loop you are calling finish() which is causing your current activity instance to be destroyed thus going to previous activity.
I hope this helps you.