AutoCOmplete Edittext in Android - java

i want type msg as well as it shows autoCompletetext of names( what I have in my database) in single Edittext android . Is it possible ?
example :--
My name is Amit. I live in Delhi.
So in this above sentence Amit should come from AutoComplete which is in my database. and rest of words are normal typed.

You can use AutoCompleteTextView
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="ID:" />
<AutoCompleteTextView
android:id="#+id/autoID"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="PW:" />
<AutoCompleteTextView
android:id="#+id/autoPW"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="textPassword" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btnSubmit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Submit" />
<Button
android:id="#+id/btnCancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel" />
</LinearLayout>
And Activity:
private Button btnSubmit, btnCancel;
private AutoCompleteTextView autoID, autoPW;
private ListView lvID;
private Button btnListID;
private EditText editID;
private ArrayList<String> arrID = new ArrayList<String>();
private ArrayAdapter<String> adapterID = null;
private ArrayList<String> arrPW = new ArrayList<String>();
private ArrayAdapter<String> adapterPW = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCache(autoID.getText().toString());
}
});
btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
autoID.setText("");
autoPW.setText("");
}
});
autoID = (AutoCompleteTextView) findViewById(R.id.autoID);
autoPW = (AutoCompleteTextView) findViewById(R.id.autoPW);
getCache();
}
private void getCache() {
SharedPreferences prefs = getSharedPreferences("LOGINS", MODE_PRIVATE);
int total_ID = prefs.getInt("COUNT_ID", 0);
while (total_ID>0) {
String id = prefs.getString(createKEY(total_ID), null);
if (id != null) {
arrID.add(id);
}
total_ID -=1;
}
adapterID = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, arrID);
autoID.setAdapter(adapterID);
}
private void addCache(String data) {
for (int i = 0; i < arrID.size(); i++) {
String str = arrID.get(i);
if (str.trim().equalsIgnoreCase(data.trim())) {
return;
}
}
arrID.add(data);
adapterID = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, arrID);
autoID.setAdapter(adapterID);
putIntSharedPreferences("COUNT_ID", arrID.size());
putStringSharedPreferences(createKEY(arrID.size()), data);
}
private String createKEY(int total) {
String key = "ID"+total;
return key;
}
private void putIntSharedPreferences(String key, int value) {
SharedPreferences preferences = getSharedPreferences("LOGINS",
MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(key, value);
editor.commit();
}
private void putStringSharedPreferences(String key, String values) {
SharedPreferences preferences = getSharedPreferences("LOGINS",
MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, values);
editor.commit();
}
private String getSharedPreferences(String key) {
SharedPreferences preferences = getSharedPreferences("LOGINS",
MODE_PRIVATE);
return preferences.getString(key, "VALUE 1");
}
I used SharedPreferences to save ID when onclick to Submit button.

Related

Save data on button click using Shared Preferences

I am working on an activity, my goal is that by clicking the save button it shows me the data, entered values and clicking the edit button allows me to edit the data, saved values. I have some TextView and EditText and 2 buttons.
´´´
public class MyInfo extends AppCompatActivity {
SharedPreferences sharedpreferences;
TextView name;
TextView address;
TextView firstContactName;
TextView firstContactPhoneNumber;
TextView secondContactName;
TextView secondContactPhoneNumber;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Address = "addressKey";
public static final String FirstContactName = "firstContactNameKey";
public static final String SecondContactName = "secondContactNameKey";
public static final String FirstContactPhoneNumber = "firstContactPhoneNumberKey";
public static final String SecondContactPhoneNumber = "secondContactPhoneNumber";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_info);
name = (TextView) findViewById(R.id.edit_text_my_name);
address = (TextView) findViewById(R.id.edit_text_my_address);
firstContactName = (TextView) findViewById(R.id.edit_text_first_contact_name);
firstContactPhoneNumber = (TextView) findViewById(R.id.edit_text_first_contact_phone);
secondContactName = (TextView) findViewById(R.id.edit_text_second_contact_name);
secondContactPhoneNumber = (TextView) findViewById(R.id.edit_text_second_contact_phone);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Address)) {
address.setText(sharedpreferences.getString(Address, ""));
}
if (sharedpreferences.contains(FirstContactName)) {
firstContactName.setText(sharedpreferences.getString(FirstContactName, ""));
}
if (sharedpreferences.contains(FirstContactPhoneNumber)) {
firstContactPhoneNumber.setText(sharedpreferences.getString(FirstContactPhoneNumber, ""));
}
if (sharedpreferences.contains(SecondContactName)) {
secondContactName.setText(sharedpreferences.getString(SecondContactName, ""));
}
if (sharedpreferences.contains(SecondContactPhoneNumber)) {
secondContactPhoneNumber.setText(sharedpreferences.getString(SecondContactPhoneNumber, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String a = address.getText().toString();
String fcn = firstContactName.getText().toString();
String fcpn = firstContactPhoneNumber.getText().toString();
String scn = secondContactName.getText().toString();
String scpn = secondContactPhoneNumber.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Address, a);
editor.putString(FirstContactName, fcn);
editor.putString(FirstContactPhoneNumber, fcpn);
editor.putString(SecondContactName, scn);
editor.putString(SecondContactPhoneNumber, scpn);
editor.apply();
name = (TextView) findViewById(R.id.edit_text_my_name);
address = (TextView) findViewById(R.id.edit_text_my_address);
firstContactName = (TextView) findViewById(R.id.edit_text_first_contact_name);
firstContactPhoneNumber = (TextView) findViewById(R.id.edit_text_first_contact_phone);
secondContactName = (TextView) findViewById(R.id.edit_text_second_contact_name);
secondContactPhoneNumber = (TextView) findViewById(R.id.edit_text_second_contact_phone);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Address)) {
address.setText(sharedpreferences.getString(Address, ""));
}
if (sharedpreferences.contains(FirstContactName)) {
firstContactName.setText(sharedpreferences.getString(FirstContactName, ""));
}
if (sharedpreferences.contains(FirstContactPhoneNumber)) {
firstContactPhoneNumber.setText(sharedpreferences.getString(FirstContactPhoneNumber, ""));
}
if (sharedpreferences.contains(SecondContactName)) {
secondContactName.setText(sharedpreferences.getString(SecondContactName, ""));
}
if (sharedpreferences.contains(SecondContactPhoneNumber)) {
secondContactPhoneNumber.setText(sharedpreferences.getString(SecondContactPhoneNumber, ""));
}
}
}
´´´
I have thought about it but I can't make it work, I don't know what is wrong with my java code
´´´
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/padding_left_right"
android:paddingRight="#dimen/padding_left_right"
android:paddingTop="#dimen/padding_top_bottom"
android:paddingBottom="#dimen/padding_top_bottom"
android:orientation="vertical"
tools:context=".MyInfo">
<TextView
android:id="#+id/text_view_my_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/my_name"
android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
<EditText
android:id="#+id/edit_text_my_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_my_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/my_address"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_my_address"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_first_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/first_contact_name"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_first_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_first_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/first_contact_phone"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_first_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_second_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/second_contact_name"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_second_contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_view_second_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/second_contact_phone"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
<EditText
android:id="#+id/edit_text_second_contact_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<Button
android:id="#+id/edit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Clear"
android:text="#string/edit_button" />
<Button
android:id="#+id/save_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Save"
android:text="#string/save_button" />
</LinearLayout>
</LinearLayout>
´´´
first initial your widget then save values on share preference
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Address)) {
address.setText(sharedpreferences.getString(Address, ""));
}
if (sharedpreferences.contains(FirstContactName)) {
firstContactName.setText(sharedpreferences.getString(FirstContactName, ""));
}
if (sharedpreferences.contains(FirstContactPhoneNumber)) {
firstContactPhoneNumber.setText(sharedpreferences.getString(FirstContactPhoneNumber, ""));
}
if (sharedpreferences.contains(SecondContactName)) {
secondContactName.setText(sharedpreferences.getString(SecondContactName, ""));
}
if (sharedpreferences.contains(SecondContactPhoneNumber)) {
secondContactPhoneNumber.setText(sharedpreferences.getString(SecondContactPhoneNumber, ""));
}
name = (TextView) findViewById(R.id.edit_text_my_name);
address = (TextView) findViewById(R.id.edit_text_my_address);
firstContactName = (TextView) findViewById(R.id.edit_text_first_contact_name);
firstContactPhoneNumber = (TextView) findViewById(R.id.edit_text_first_contact_phone);
secondContactName = (TextView) findViewById(R.id.edit_text_second_contact_name);
secondContactPhoneNumber = (TextView) findViewById(R.id.edit_text_second_contact_phone);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
String n = name.getText().toString();
String a = address.getText().toString();
String fcn = firstContactName.getText().toString();
String fcpn = firstContactPhoneNumber.getText().toString();
String scn = secondContactName.getText().toString();
String scpn = secondContactPhoneNumber.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Address, a);
editor.putString(FirstContactName, fcn);
editor.putString(FirstContactPhoneNumber, fcpn);
editor.putString(SecondContactName, scn);
editor.putString(SecondContactPhoneNumber, scpn);
editor.apply();
All your text strings seems to be coming from 'TextView'. I can't see the 'EditText' where you would edit the values. Change the values you want to be editable to be displayed in 'EditText' instead of 'TextView'.

Integer value not being saved to Preference XML not displaying the value

I'm currently developing a calorie app for my class project. I am having issues saving the value from the profile function calculateTDEE to the shared preference xml. The page i'm currently working on gets information from the user and depending what the user selects determines their calories. That value is then saved in shared preference where it is displayed in the main activity.
I'm still learning android studio and this is my first app I'm developing.
Thank you in advance.
profile java file
`public class Profile extends Fragment implements View.OnClickListener {
//adaptors spinners
ArrayAdapter<String> HeightFeetAdapter;
ArrayAdapter<String> WeightLBSAdapter;
//references UI elements
Button SaveButton;
Spinner weightSpinner;
Spinner heightSpinner;
Spinner goal;
Spinner gender;
Spinner activityLevel;
EditText age;
private Animation anim;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_profile, container,
false);
String username =
getActivity().getIntent().getStringExtra("Username");
TextView userMain = (TextView) myView.findViewById(R.id.User);
userMain.setText(username);
age =(EditText)myView.findViewById(R.id.editText3);
age.setInputType(InputType.TYPE_CLASS_NUMBER);
heightSpinner = (Spinner) myView.findViewById(R.id.HeightSpin);
weightSpinner = (Spinner) myView.findViewById(R.id.WeightSpin);
activityLevel = (Spinner) myView.findViewById(R.id.activity_level);
ArrayAdapter<CharSequence> adapter_activity =
ArrayAdapter.createFromResource(getActivity(),
R.array.activity_level, android.R.layout.simple_spinner_item);
adapter_activity.setDropDownViewResource
(android.R.layout.simple_spinner_dropdow
n_item);
activityLevel.setAdapter(adapter_activity);
goal = (Spinner) myView.findViewById(R.id.goal);
ArrayAdapter<CharSequence> adapter_goal =
ArrayAdapter.createFromResource(getActivity(),
R.array.goal, android.R.layout.simple_spinner_item);
adapter_goal.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
goal.setAdapter(adapter_goal);
gender = (Spinner) myView.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter_gender =
ArrayAdapter.createFromResource(getActivity(),
R.array.gender, android.R.layout.simple_spinner_item);
adapter_gender.setDropDownViewResource
(android.R.layout.simple_list_item_activated_1);
gender.setAdapter(adapter_gender);
SaveButton = (Button) myView.findViewById(R.id.savebutton);
SaveButton.setOnClickListener(this);
initializeSpinnerAdapters();
loadLBVal();
loadFTVal();
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
heightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
weightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
SaveButton.startAnimation(anim);
SharedPreferences userInfo =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
return myView;
}
public void loadLBVal() {
weightSpinner.setAdapter(WeightLBSAdapter);
// set the default lib value
weightSpinner.setSelection(WeightLBSAdapter.getPosition("170"));
}
// load the feets value range to the height spinner
public void loadFTVal() {
heightSpinner.setAdapter(HeightFeetAdapter);
// set the default value to feets
heightSpinner.setSelection(HeightFeetAdapter.getPosition("5\"05'"));
}
public void initializeSpinnerAdapters() {
String[] weightLibs = new String[300];
// loading spinner values for weight
int k = 299;
for (int i = 1; i <= 300; i++) {
weightLibs[k--] = String.format("%3d", i);
}
// initialize the weightLibsAdapter with the weightLibs values
WeightLBSAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, weightLibs);
WeightLBSAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
String[] heightFeets = new String[60];
// loading values 3"0' to 7"11' to the height in feet/inch
k = 59;
for (int i = 3; i < 8; i++) {
for (int j = 0; j < 12; j++) {
heightFeets[k--] = i + "\"" + String.format("%02d", j) + "'";
}
}
// initialize the heightFeetAdapter with the heightFeets values
HeightFeetAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, heightFeets);
HeightFeetAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.savebutton:
int activityLevel, goal, gender, age;
// Get preferences
float height = getSelectedHeight();
float weight = getSelectedWeight();
activityLevel =
((Spinner)getActivity().findViewById
(R.id.activity_level)).getSelectedItemPosition();
goal = ((Spinner)getActivity().
findViewById(R.id.goal)).getSelectedItemPosition();
gender= ((Spinner)getActivity().
findViewById(R.id.gender)).getSelectedItemPosition();
age = Integer.parseInt(((EditText).
getActivity().findViewById(R.id.editText3)));
int tdee = calculateTDEE(height,weight,activityLevel,age,gender,
goal);
// Save preferences in XML
SharedPreferences userInfo = getSharedPreferences("userInfo",
0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
break;
}
}
public float getSelectedWeight() {
String selectedWeightValue = (String)weightSpinner.getSelectedItem();
return (float) (Float.parseFloat(selectedWeightValue) * 0.45359237);
}
public float getSelectedHeight() {
String selectedHeightValue = (String)heightSpinner.getSelectedItem();
// the position is feets and inches, so convert to meters and return
String feets = selectedHeightValue.substring(0, 1);
String inches = selectedHeightValue.substring(2, 4);
return (float) (Float.parseFloat(feets) * 0.3048) +
(float) (Float.parseFloat(inches) * 0.0254);
}
public int calculateTDEE(float height, float weight, int activityLevel,
int
age, int gender, int goal) {
double bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5;
if(gender == 1) {
bmr = (10* weight) + (6.25 * height) - (5*age) - 161;
}
double activity = 1.25;
switch(activityLevel) {
case 1:
activity = 1.375;
break;
case 2:
activity = 1.55;
break;
case 3:
activity = 1.725;
break;
case 4:
activity = 1.9;
break;
}
double tdee = bmr * activity;
switch(goal) {
case 0:
tdee -=500;
break;
case 2:
tdee +=500;
break;
}
tdee += .5;
return (int) tdee;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
`
fragment_profile xml
`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/imgbackground2"
android:weightSum="1">
<TextView
android:layout_width="180dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/tv_main_title" />
<TextView
android:layout_width="294dp"
android:layout_height="65dp"
android:text="Please Complete Information"
android:textColor="#color/colorBackground"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:textSize="20dp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Age"
android:id="#+id/textView12"
android:layout_above="#+id/gender"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<EditText
android:layout_width="50dp"
android:layout_height="50dp"
android:inputType="number"
android:ems="10"
android:id="#+id/editText3"
android:imeOptions="actionDone"
android:layout_alignTop="#+id/gender"
android:layout_alignLeft="#+id/editText"
android:layout_marginLeft="0dp"
android:layout_column="1" />
</TableRow>
</TableLayout>
<RelativeLayout
android:layout_width="194dp"
android:layout_height="26dp"></RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Gender"
android:id="#+id/textView11"
/>
<Spinner
android:layout_width="113dp"
android:layout_height="40dp"
android:id="#+id/gender"
android:layout_above="#+id/textView5"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_alignStart="#+id/textView4"
android:layout_alignEnd="#+id/textView3"
android:spinnerMode="dropdown"
android:popupBackground="#color/colorBackground" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="329dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/weightLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:paddingRight="0dp"
android:paddingLeft="-2dp" />
<Spinner
android:id="#+id/WeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/weightLabel"
android:spinnerMode="dropdown"
android:layout_weight="2"
android:textAlignment="center"
android:popupBackground="#drawable/graybackground2"
android:layout_span="2"
android:layout_column="1" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/heightLabel"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:layout_column="0"
android:layout_marginLeft="5dp" />
<Spinner
android:id="#+id/HeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/heightLabel"
android:layout_weight="2"
android:popupBackground="#drawable/graybackground2"
android:spinnerMode="dropdown"
android:layout_marginTop="0dp"
android:layout_margin="0dp"
android:layout_marginBottom="0dp"
android:layout_column="1"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:textAlignment="center"
android:paddingStart="5dp"
android:layout_marginLeft="0dp"
android:layout_span="0"
android:layout_marginRight="0dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Activity Level"
android:id="#+id/textView7"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/activity_level"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Goal"
android:id="#+id/textView8"
android:layout_below="#+id/activity_level"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/goal"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/savebutton"
android:radius="10dp"
android:textColor="#color/colorBackground"
android:onClick="saveAction"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/editText3"
android:layout_gravity="right" />
</LinearLayout>
`
Fragmenthome.java
import java.util.ArrayList;
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
private Animation anim;
ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;
int goalCalories;
int totalCalorie;
Button mButton;
//Database
private DatabaseHandler dba;
private ArrayList<Food> dbFoods = new ArrayList<>();
private CustomListViewAdapter foodAdapter;
private Food myFood ;
//fragment
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
caloriesTotal = (TextView) myView.findViewById(R.id.tv_calorie_amount);
caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
listView = (ListView) myView.findViewById(R.id.ListId);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain) getActivity()).loadSelection(4);
}
});
ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);
ResetEntry.setOnClickListener(this);
refreshData();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
return myView;
}
public void reset () {
//
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.clear();
dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
public void refreshData (){
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
totalCalorie = dba.totalCalories();
String formattedCalories = Utils.formatNumber(totalCalorie);
String formattedRemain = Utils.formatNumber(goalCalories -
totalCalorie);
//setting the editTexts:
caloriesTotal.setText("Total Calories: " + formattedCalories);
caloriesRemain.setText(formattedRemain);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.add(myFood);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
//save prefs
public void savePrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
//get prefs
public int loadPrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
return sharedPreferences.getInt(key, value);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
case R.id.action_settings:
Intent preferenceScreenIntent = new Intent(getContext(),
PreferenceScreenActivity.class);
startActivity(preferenceScreenIntent);
break;
case R.id.ResetEntry:
reset();
anim= AnimationUtils.loadAnimation(getActivity(),
R.anim.fading);
listView.startAnimation(anim);
break;
}
}
}
preference.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="User Settings">
<EditTextPreference
android:title="Daily Calorie Amount"
android:inputType="number"
android:defaultValue="2000"
android:key="#string/prefs_key_daily_calorie_amount"
android:summary="#string/prefs_description_daily_calorie_amount" />
</PreferenceCategory>
</PreferenceScreen>
ok, so you have lines
SharedPreferences userInfo = getSharedPreferences("userInfo", 0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
which are storing your value in SharedPreferences. where do you have fetching this value? (smth like below)
int tdee = getSharedPreferences("userInfo", 0).getInt("tdee");
why do you say that int isn't stored? in my opinion is stored perfectly and you are not trying to restore it in e.g. onCreate at all (basing on posted code)
also: try to clear your code before posting question/answer, strip code from unnecesary and not related to problem lines

Country code is not getting from country code picker in Android

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");

Retrofit error in Android

I am trying to create a login page. Onclick of the button, I am calling a method to verify the login credentials if already present in the backend django server. I am able to fetch the values of the username and password. The problem that I am currently facing is, if I give the login credentials already present in the backend server, the application works fine. But if I give login credentials which are not in the backend database, the application crashes. Kindly help
Code for Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/login_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/login_background"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/appName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:text="Teacher Diary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="By"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<ImageView
android:id="#+id/logo"
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_gravity="center"
android:contentDescription="#string/home_screen_description"
android:src="#drawable/lo_logo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="25dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_username"
android:singleLine="true"
android:textColor="#color/blue" />
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_password"
android:imeOptions="actionGo"
android:inputType="textPassword"
android:textColor="#color/blue" />
<Button
android:id="#+id/btLogin"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_background"
android:text="#string/login"
android:textColor="#color/white"
android:textSize="20dp" />
<TextView
android:id="#+id/tvDisplayMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:text="The easiest way to conduct assessments!"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
Code for login.java
public class Login extends Activity implements View.OnClickListener {
private SQLiteDatabase m_database;
private LODatabaseHelper m_databaseHelper;
private Button m_btLogin;
private Animation m_anim;
private EditText m_etUsername, m_etPassword;
private String m_username, m_password, m_role, m_schoolId;
private TextView m_displayMessage;
private String ACCESS_TOKEN = "f59Gh28E6#2h13Y";
private static RequestToServiceCallback mGetRequestToServiceCallback;
public static void setCallback(RequestToServiceCallback callback) {
mGetRequestToServiceCallback = callback;
}
public interface RequestToServiceCallback {
void statusReporting(int id);
void stopService();
}
boolean login = true;
ProgressDialog pDialog;
//List of type books this list will store type Book which is our data model
private static List<LoginModel> logindata;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().hide();
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC25AAE2")));
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextSize(15.5f);
abTitle.setTextColor(Color.WHITE);
SharedPreferences prefs = this.getSharedPreferences("global_settings",
Context.MODE_PRIVATE);
m_username = prefs.getString("username", "");
m_role = prefs.getString("role", "");
if (m_username.contentEquals("")) {
// do Nothing and continue further the user hasn't logged in yet.
// mSync.adminSync("2");
} else {
Intent intent;
if (m_role.contentEquals("admin"))
intent = new Intent(getApplicationContext(), AdminSync.class);
else
intent = new Intent(getApplicationContext(), Home.class);
finish();
startActivity(intent);
}
setContentView(R.layout.login);
/** Initialise m_database variables */
m_databaseHelper = LODatabaseHelper.getHelper(getApplicationContext());
m_database = m_databaseHelper.getWritableDatabase();
LODatabaseUtility.getInstance().setDatabase(m_database);
m_btLogin = (Button) findViewById(R.id.btLogin);
m_btLogin.setOnClickListener(this);
m_displayMessage = (TextView) findViewById(R.id.tvDisplayMessage);
m_etUsername = (EditText) findViewById(R.id.etUserName);
m_etPassword = (EditText) findViewById(R.id.etPassword);
/* Put the last login credentials into the edit texts */
String lastUsername = prefs.getString("username_last", "");
String lastPassword = prefs.getString("password_last", "");
if (lastUsername.contentEquals("")) {
/* Do Nothing */
} else {
m_etUsername.setText(lastUsername);
m_etPassword.setText(lastPassword);
}
setAnimationValue();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void setAnimationValue() {
m_anim = new AlphaAnimation(0.0f, 1.0f);
m_anim.setDuration(100); // You can manage the time of the blink with
// this parameter
m_anim.setStartOffset(20);
m_anim.setRepeatMode(Animation.REVERSE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btLogin:
/* check the username and password */
if (m_etUsername.getText().length() == 0) {
m_displayMessage.setText("Enter User Name");
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Name and Password");
}
return;
}
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Password");
return;
}
m_username = m_etUsername.getText().toString();
m_password = m_etPassword.getText().toString();
//Calling the method that will fetch data
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
break;
}
}
private void getLoginDetails(final String m_username, final String m_password, final String ACCESS_TOKEN) {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(Login.this, "Please wait... ", "Login in progress", false, false);
Log.e("m_username:", m_username);
Log.e("m_password:", m_password);
App.getRestClient()
.getLoginService()
.getLoginData(m_username, m_password, ACCESS_TOKEN,
new Callback<List<LoginAPIModel>>() {
#Override
public void failure(RetrofitError arg0) {
if(arg0.getKind() == RetrofitError.Kind.CONVERSION || arg0.getKind() == RetrofitError.Kind.NETWORK){
Log.e("Exception","");
}
/*Log.e( "TAG" + "ERROR", "Logindetails table: start = "
+ "" + retrofitError.getMessage());
if (retrofitError.getKind() == RetrofitError.Kind.CONVERSION
|| retrofitError.getKind() == RetrofitError.Kind.NETWORK) {
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
} else {
mGetRequestToServiceCallback.stopService();
}*/
}
#Override
public void success(List<LoginAPIModel> arg0,
Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.e("schoolid", arg0.get(0).getSchoolId());
Log.e("username:", arg0.get(0).getUsername());
Log.e("role:", arg0.get(0).getRole());
SharedPreferences prefs = getSharedPreferences(
"global_settings",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("school_id",
arg0.get(0).getSchoolId());
editor.putString("username",
arg0.get(0).getUsername());
editor.putString("password",
arg0.get(0).getPassword());
editor.putString("role",
arg0.get(0).getRole());
editor.putString("email",
arg0.get(0).getEmail());
editor.putString("user",
arg0.get(0).getUser());
editor.putString("otp",
arg0.get(0).getOtp());
editor.putString("telephone_no",
arg0.get(0).getTelephoneNo());
editor.commit();
String temp1 = arg0.get(0).getRole();
Log.e("Temp1 values:", temp1);
String tempUsername=arg0.get(0).getUsername();
Log.e("username values:", tempUsername);
String tempPassword=arg0.get(0).getPassword();
Log.e("password values:", tempPassword);
Intent intent = null;
if (temp1.contentEquals("admin")) {
intent = new Intent(Login.this, AdminSync.class);
intent.putExtra("mSchoolId", m_schoolId);
finish();
startActivity(intent);
new loginUser().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else if (temp1.contentEquals("teacher")) {
loading.dismiss();
m_displayMessage.setText("Invalid username password !");
} else {
//intent = new Intent(Login.this, Home.class);
}
//
}
});
}
My Logcat:
05-03 13:02:17.156 13719-13719/? E/m_username:: GChjvbj
05-03 13:02:17.156 13719-13719/? E/m_password:: chknmnvv
05-03 13:02:17.293 7409-7419/? E/Parcel: Reading a NULL string not supported here.
05-03 13:02:17.555 13719-13719/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.learningoutcomes, PID: 13719
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.learningoutcomes.Login$1.success(Login.java:206)
at com.learningoutcomes.Login$1.success(Login.java:184)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)

Android Pagination ListView

Hi i have trouble in achieving pagination for listview in android. My task is to add Values from editTextto ListView and i need to add pagination to the list. But I tried and i am to insert only one value . While i try to add next values i end up in errors. Please kindly tell me the error on my code. i have added my layout,Activity and Log
MainActivity.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:background="#drawable/agnes2_back"
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.vivek.projectone.MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/border" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:layout_marginTop="15dp"
android:gravity="right"
android:text="#string/welcome"
android:textColor="#58FA58" />
<TextView
android:id="#+id/userView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:text="#string/userLabel"
android:textColor="#FF0000" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearlayout2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="14dp"
android:background="#drawable/border"
android:orientation="horizontal" >
<EditText
android:id="#+id/itemName"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="#+id/addButton1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/adds"
android:text="" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_alignLeft="#+id/linearlayout2"
android:layout_below="#+id/linearlayout2"
android:layout_marginTop="16dp"
android:background="#drawable/border"
android:orientation="horizontal" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="184dp"
android:layout_weight="2.32"
android:background="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"
tools:listitem="#android:layout/simple_list_item_checked" >
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="#+id/linearLayout3"
android:layout_alignParentBottom="true"
android:layout_below="#+id/linearLayout3"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_Prev"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_marginTop="10dp"
android:background="#drawable/buttonbackground"
android:text="#string/btn_prev" />
<Button
android:id="#+id/btn_Next"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:background="#drawable/buttonbackground"
android:text="#string/btn_next" />
</LinearLayout>
</RelativeLayout>
MainActivity.java
public class MultipleActivity extends Activity implements OnItemClickListener {
Button addToList;
EditText viewListItem1, viewListItem2;
ListView customItemList;
PackageManager packageManager;
ArrayList<String> checkedCustomItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple);
addToList = (Button) findViewById(R.id.adToListBtn);
viewListItem1 = (EditText) findViewById(R.id.viewEditItem1);
viewListItem2 = (EditText) findViewById(R.id.viewEditItem2);
packageManager = getPackageManager();
final List<PackageInfo> packageList = packageManager
public class MainActivity extends Activity {
String userLabel;
EditText itemName;
Button addBut;
Button multipleBtn;
ListView itemList;
private ArrayList<String> itemAList;
ArrayAdapter<String> itemAdapter;
private int pageCount;
private Button buttonPrev;
private Button buttonNext;
private int increment = 0;
public int TOTAL_LIST_ITEMS = 1030;
public int NUM_ITEMS_PAGE = 5;
String item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.userView);
itemName = (EditText) findViewById(R.id.itemName);
addBut = (Button) findViewById(R.id.addButton1);
buttonNext = (Button) findViewById(R.id.btn_Next);
buttonPrev = (Button) findViewById(R.id.btn_Prev);
itemList = (ListView) findViewById(R.id.listView1);
buttonPrev.setEnabled(false);
multipleBtn = (Button) findViewById(R.id.multipleValsBtn);
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0 ? 0 : 1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE + val;
Intent intent = getIntent();
userLabel = intent.getExtras().getString("emailID");
textView.setText(userLabel);
itemAList = new ArrayList<>();
itemAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, itemAList);
itemList.setAdapter(itemAdapter);
itemList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
item = itemAList.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
buttonNext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
increment++;
loadList(increment);
CheckEnable();
}
});
buttonPrev.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
increment--;
loadList(increment);
CheckEnable();
}
});
addBut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
item = itemName.getText().toString();
itemAList.add(0, item);
loadList(0);
itemName.setText("");
}
});
multipleBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
MultipleActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void CheckEnable() {
if (increment + 1 == pageCount) {
buttonNext.setEnabled(false);
} else if (increment == 0) {
buttonPrev.setEnabled(false);
} else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
private void loadList(int number) {
ArrayList<String> sort = new ArrayList<String>();
int start = number * NUM_ITEMS_PAGE;
for (int i = start; i < (start) + NUM_ITEMS_PAGE; i++) {
if (i < itemAList.size()) {
sort.add(itemAList.get(i));
} else {
break;
}
}
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
itemList.setAdapter(itemAdapter);
}
}
You need to use setAdapter only once. For changing the list item next time (for loading next 5 items), you just need to use next notifyDataSetChanged
private void loadList(int number) {
ArrayList<String> sort = new ArrayList<String>();
int start = number * NUM_ITEMS_PAGE;
for (int i = start; i < (start) + NUM_ITEMS_PAGE; i++) {
if (i < itemAList.size()) {
sort.add(itemAList.get(i));
} else {
break;
}
}
if(itemAdapter ==null){
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
itemList.setAdapter(itemAdapter);
}
else{
itemAdapter.notifyDataSetChanged();
}
}
Though I didn't get what you are doing, but try to do this change:
Remove this line
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
or Add add one more line below this line
itemList.setAdapter(itemAdapter);
Because you have already called :itemAdapter.notifyDataSetChanged(); it should update the list.

Categories