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
Related
I want to be able to add multiple values on a list but properly style the list view.
For example right now the list view will look like this:
namepostcodedate
which is because of the following code
ListArray.add(jobs.get(finalJ).customer.getName() + job.getPostcode() + job.getDate());
The way that I am currently adding the values in the ListArray doesn't seem ideal but I am not sure if there is another way to do this and display the list formated?
This is my list_item file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TableRow
android:id="#+id/rows2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ddOrangeLight"
android:showDividers="middle">
<!-- android:divider="?android:attr/dividerHorizontal"-->
<TextView
android:id="#+id/customerNameView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="4sp"
android:layout_marginTop="10dp"
android:layout_marginEnd="4sp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</RelativeLayout>
My adapter class
public class SearchableAdapter extends BaseAdapter implements Filterable {
private List<String>originalData = null;
private List<String>filteredData = null;
private final LayoutInflater mInflater;
private final ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<String> data) {
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.uName = (TextView) convertView.findViewById(R.id.customerNameView);
// holder.uPostCode = (TextView) convertView.findViewById(R.id.postCode);
// holder.UDateTime = (TextView) convertView.findViewById(R.id.dateTimeView);
// Bind the data efficiently with the holder.
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// If weren't re-ordering this you could rely on what you set last time
// holder.text.setText(filteredData.get(position));
holder.uName.setText(filteredData.get(position));
// holder.uPostCode.setText(filteredData.get(position));
// holder.UDateTime.setText(filteredData.get(position));
return convertView;
}
static class ViewHolder {
TextView uName;
// TextView uPostCode;
// TextView UDateTime;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Fragment class
public class CompletedJobsFragment extends Fragment {
AppActivity a;
String search;
TableLayout tableLayout;
Vehicle vehicle;
ListView listView;
SearchableAdapter arrayAdapter;
EditText searchInput;
List<String> ListArray = new ArrayList<String>();
ArrayList<ListItem> results = new ArrayList<>();
ListItem repairDetails = new ListItem();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_completed_jobs,container,false);
a = (AppActivity) getActivity();
assert a != null;
tableLayout = (TableLayout) v.findViewById(R.id.completedJobsTable);
Button clear = v.findViewById(R.id.btnClearTextCarReg);
searchInput = v.findViewById(R.id.txtEditSearchCarReg);
listView = v.findViewById(R.id.list__View);
search = searchInput.getText().toString().trim();
clear.setOnClickListener(av -> searchInput.setText(""));
// Button searchButton = v.findViewById(R.id.btnSearchVehicleReg);
arrayAdapter = new SearchableAdapter(getContext(),ListArray);
listView.setAdapter(arrayAdapter);
listView.setClickable(true);
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
arrayAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
JobRepository jobRepository = new JobRepository(a.getApplication());
VehicleRepository vehicleRepository = new VehicleRepository(a.getApplication());
jobRepository.findCompleted().observe(getViewLifecycleOwner(), jobs -> {
for (int j = 0; j < jobs.size(); j++) {
if (jobs.get(j).job == null) {
continue;
}
int finalJ = j;
vehicleRepository.findByJob(jobs.get(j).job.getUuid()).observe(getViewLifecycleOwner(), vehicles -> {
for (int vh = 0; vh < vehicles.size(); vh++) {
if (vehicles.get(vh).vehicle == null) {
continue;
}
vehicle = vehicles.get(vh).vehicle;
Job job = jobs.get(finalJ).job;
ListArray.add(jobs.get(finalJ).customer.getName() + job.getPostcode() + job.getDate());
View viewToAdd = arrayAdapter.getView(finalJ, null, null);
TableRow[] tableRows = new TableRow[jobs.size()];
tableRows[finalJ] = new TableRow(a);
tableRows[finalJ].setId(finalJ + 1);
tableRows[finalJ].setPadding(0, 20, 0, 20);
tableRows[finalJ].setBackgroundResource(android.R.drawable.list_selector_background);
tableRows[finalJ].setBackgroundResource(R.drawable.table_outline);
tableRows[finalJ].setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT
));
tableRows[finalJ].addView(viewToAdd);
tableLayout.addView(tableRows[finalJ], new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT
));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
// Toast.makeText(getContext(), "asd", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString(JOB_ID, job.getUuid().toString());
bundle.putString(CUSTOMER_NAME, jobs.get(finalJ).customer.getName());
// bundle.putString(JOB_DATE, sdf.format(job.getDate()));
Fragment fragment = new ViewCustomerInformationFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
}
});
}
});
return v;
}
Fragment xml file
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imageViewBGhm"
android:scaleType="center"
android:orientation="vertical"
android:background="#color/white">
<TextView
android:id="#+id/txtTitle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="180dp"
android:text="#string/completed_jobs"
android:textColor="#color/ddGrey"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.375"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/txtEditSearchCarReg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txtTitle2"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="16dp"
android:ems="12"
android:inputType="textPersonName"
android:paddingStart="5dp"
android:paddingEnd="10dp"
android:paddingBottom="22dp"
android:textAlignment="textStart"
android:textSize="18sp" />
<TableRow
android:id="#+id/tableTitleRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtEditSearchCarReg"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="6dp"
android:background="#color/lightGrey"
android:divider="?android:attr/dividerHorizontal"
android:showDividers="middle"
android:visibility="visible">
<TextView
android:id="#+id/txtCustomerNameTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginStart="4sp"
android:layout_marginTop="10dp"
android:layout_marginEnd="4sp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/customer_name_hc"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtPostcodeTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/postcode_placeholder"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtDateTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/date"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtTimeTitle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginEnd="20sp"
android:layout_marginBottom="10dp"
android:layout_weight="1"
android:gravity="center"
android:text="#string/enquiry_vat_value"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
</TableRow>
<ListView
android:id="#+id/list__View"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="#id/tableTitleRow"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:visibility="visible" />
<TableLayout
android:id="#+id/completedJobsTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txtEditSearchCarReg"
android:layout_marginStart="2dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="2dp"
android:layout_marginBottom="2dp"
android:stretchColumns="0,1,2"
android:visibility="gone">
</TableLayout>
<Button
android:id="#+id/btnClearTextCarReg"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignTop="#+id/txtEditSearchCarReg"
android:layout_alignParentEnd="true"
android:layout_marginStart="175dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="20dp"
android:background="#drawable/ic_outline_cancel_24"
android:backgroundTint="#color/ddOrange"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground" />
<Button
android:id="#+id/btnSearchVehicleReg"
style="#style/DDButtons"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/txtEditSearchCarReg"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="14dp"
android:background="#drawable/custom_buttons"
android:drawableStart="#drawable/ic_outline_search_24"
android:drawablePadding="12dp"
android:letterSpacing="0.2"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:singleLine="true"
android:text="#string/search_postcode"
android:textAlignment="textStart"
android:textSize="18sp"
android:textStyle="bold"
android:visibility="gone"/>
</RelativeLayout>
I am Parvanshu Sharma and I am a beginner to programming, I am making an application in which
I have done that on button click a date Picker dialog will appear and the button text will be set to the selected by the user, Currently there are 3 buttons for this and I even have a realtime database for uploading this date on Firebase, but now I am having problems in getting the every unique date and uploading it, I am not able to get the selected date.
And as my every stackoverflow question has-
MainActivity.java (Its too big so I haven't shown imports)
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString()+"/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
if (Quantity1.getSelectedItem().toString() != "0") {
//I want some solution HERE
}
}
});
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}```
and here goes my activity_main.xml
```<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/NameTextView"
android:layout_width="93dp"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"
android:layout_marginTop="10sp"
android:text="Name"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonName"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName" />
<TextView
android:id="#+id/PhoneTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="Mobile Number"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonPhone"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Mobile number"
android:inputType="phone" />
<TextView
android:id="#+id/AddressTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="Address"
android:textColor="#color/black"
android:textSize="28sp"
android:textStyle="bold" />
<EditText
android:id="#+id/PersonAddress"
android:layout_width="328dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:ems="10"
android:hint="Delivery Address"
android:inputType="textPostalAddress" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:text=" Order Details"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<TableLayout
android:id="#+id/MainTable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:stretchColumns="0,1,2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="0"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text=" Date "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text="Item"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="2"
android:layout_margin="1dp"
android:background="#FFFFFF"
android:gravity="center"
android:text="Quantity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem1"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center"
android:text="Select Item" />
<Spinner
android:id="#+id/SelectQuantity1"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem2"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center"
android:text="Select Item" />
<Spinner
android:id="#+id/SelectQuantity2"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#000000">
<Button
android:id="#+id/SelectDateButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select" />
<Spinner
android:id="#+id/SelectItem3"
android:layout_width="40dp"
android:layout_height="43dp"
android:layout_marginStart="3dp"
android:layout_marginLeft="3dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:background="#color/white"
android:gravity="center" />
<Spinner
android:id="#+id/SelectQuantity3"
android:layout_width="40dp"
android:layout_height="43dp"
android:background="#color/white"
android:gravity="center" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/DoneButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
and I have one more class for creating DatePickerDialog,
the source from where I learnt and implemented that how to make DatePickerDialog is Here
which goes here- (DatePickerFragment.java)
public class DatePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
}
}
Tried using an interface. You will have all 3 dates in your main activity, now you can do whatever with them
public class DatePickerFragment extends DialogFragment {
private static applyDate mInterface;
private static int buttonNumberHere;
public interface applyDate {
void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber);
}
public static DatePickerFragment newInstance(int buttonNumber, applyDate context)
{
DatePickerFragment fragment = new DatePickerFragment();
mInterface = ((applyDate) context);
buttonNumberHere = buttonNumber;
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getContext(), datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
mInterface.setDate(selectedYear, selectedMonth, selectedDay, buttonNumberHere);
}
};
In MainActivity
public class MainActivity extends AppCompatActivity implements applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;// Idk what is this
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Idk how to set date but now you have all three dates
DatabaseReference dateOne = database.getReference(itemOneDate + "/DateOne");
dateOne.setValue(itemOneDate);
DatabaseReference dateTwo = database.getReference(itemOneDate + "/DateTwo");
dateTwo.setValue(itemTwoDate);
DatabaseReference dateThree = database.getReference(itemThreeDate + "/DateThree");
dateThree.setValue(itemThreeDate);
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString()+"/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
if (Quantity1.getSelectedItem().toString() != "0") {
//I want some solution HERE
}
}
});
}
#Override
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber){
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1){
itemOneDate = CurrentDateString;
}
else if (buttonNumber == 2){
itemTwoDate = CurrentDateString;
}
else if (buttonNumber == 3){
itemThreeDate = CurrentDateString;
}
}
}
I am trying to filter data from database and display filtered data into listview using cursor. Unfortunately, the cursor is returned from the query isn't empty but the items not getting displayed in the activity.And moreover, there's no error being displayed in the logcat.
My search_results.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search__results);
lview = (ListView) findViewById(R.id.list);
Intent intent = getIntent();
String from = intent.getStringExtra("from");
String to = intent.getStringExtra("to");
// String date = intent.getStringExtra("date");
// String clas = intent.getStringExtra("class");
myrailway = new no.nordicsemi.android.nrftoolbox.myRailwayAdapter(this);
// Cursor cursor = myrailway.getTrainDetails(from, to);
String[] FROM = null;
String[] TO = null;
String[] TRAINNAME = null;
String[] TRAINNO = null;
String[] DEPART = null;
String[] ARRIVAL = null;
Cursor cursor = myrailway.getTrainDetails(from, to);
if(cursor != null) {
Log.e("ERROR","NON EMPTY CURSOR");
int count = 0;
if (cursor.moveToFirst()) {
Log.e("ERROR","ENTERED LOOP");
do {
String stnfrom = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_STNFROM));
String stnto = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_STNTO));
String trainname = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_NAME));
String trainno = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_TRAINNUM));
String depart = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_DEPART));
String arrival = cursor.getString(cursor.getColumnIndex(no.nordicsemi.android.nrftoolbox.myRailwayAdapter.CONTACTS_COLUMN_ARRIVAL));
FROM[count] = stnfrom; Log.e("fr",stnfrom);
TO[count] = stnto; Log.e("too",stnto);
TRAINNAME[count] = trainname; Log.e("trainanme",trainname);
TRAINNO[count] = trainno; Log.e("trainno",trainno);
DEPART[count] = depart; Log.e("depart",depart);
ARRIVAL[count] = arrival; Log.e("arrival",arrival);
count = count + 1;
cursor.close();
} while (cursor.moveToNext());
lviewAdapter = new ListViewAdapter(this, FROM, TO, DEPART, ARRIVAL, TRAINNAME, TRAINNO);
lview.setAdapter(lviewAdapter);
}
}
else
Log.e("ERROR","EMPTY CURSOR");
}
My ListViewAdapter.java:
public class ListViewAdapter extends BaseAdapter {
Activity context;
String from[];
String to[];
String depart[];
String arrival[];
String trainname[];
String trainno[];
private no.nordicsemi.android.nrftoolbox.myRailwayAdapter myrailway;
public ListViewAdapter(Activity context, String[] from, String[] to, String[] depart, String[] arrival, String[] trainname, String[] trainno) {
super();
this.context = context;
this.from = from;
this.to = to;
this.depart = depart;
this.arrival = arrival;
this.trainname = trainname;
this.trainno = trainno;
}
#Override
public int getCount() {
return depart.length;
}
#Override
public Object getItem(int i) {
return depart[i];
}
#Override
public long getItemId(int i) {
myrailway = new no.nordicsemi.android.nrftoolbox.myRailwayAdapter(this.context);
Long recc= Long.valueOf(0);
Cursor c= myrailway.getpass(trainname[i]);
if(c!=null)
{
c.moveToFirst();
recc=c.getLong(0);
}
return recc;
}
private class ViewHolder {
TextView txtfrom;
TextView txtto;
TextView txttrainno;
TextView txttrainname;
TextView txtdepart;
TextView txtarrival;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null)
{
view = inflater.inflate(R.layout.listview_items, null);
holder = new ViewHolder();
holder.txtfrom = (TextView) view.findViewById(R.id.from);
holder.txtto = (TextView) view.findViewById(R.id.to);
holder.txttrainno = (TextView) view.findViewById(R.id.trainno);
holder.txttrainname = (TextView) view.findViewById(R.id.trainname);
holder.txtdepart = (TextView) view.findViewById(R.id.depart);
holder.txtarrival = (TextView) view.findViewById(R.id.arrival);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
holder.txtfrom.setText(from[position]);
holder.txtto.setText(to[position]);
holder.txttrainno.setText(trainno[position]);
holder.txttrainname.setText(trainname[position]);
holder.txtdepart.setText(depart[position]);
holder.txtarrival.setText(arrival[position]);
return view;
}
}
My search_results.xml:
<RelativeLayout 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"
tools:context="no.nordicsemi.android.nrftoolbox.Search_Results">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</RelativeLayout>
My listview_items.xml:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="0dip" android:layout_gravity="top"
>
<TableRow>
<TextView
android:id="#+id/from"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:textColor="#000000"
android:layout_span="1"
/>
<TextView
android:id="#+id/to"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:textColor="#000000"
android:layout_span="1"
/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="#+id/trainno"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
<TextView
android:text=""
android:id="#+id/trainname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="#+id/depart"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
<TextView
android:text=""
android:id="#+id/arrival"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="16sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
</TableLayout>
<Button
android:id="#+id/book"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:onClick="book"
android:text="BOOK">
</Button>
</TableRow>
</TableLayout>
Now, the cursor isn't empty but the listview is not displayed by the listview adapter.
Can someone point out the error in the code??
Please use this.
#Override
public int getCount() {
//here too;
return depart.lenght;
}
#Override
public Object getItem(int i) {
//there is error: repalce return null; with
return depart[i];
}
#Override
public long getItemId(int i) {
//change this too
return depart[i].getId();
}
I can see 2 reasons that this may happen:
You arrays are not filled with data/or filled with empty data and that the reason they are not presented. (less likely because you would receive a null pointer exception when you try to access a null location in the array)
Your row layout doesn't show data parameters. (I will be
on this reason, please show you row layout XML(listview_items.xml) so that we could check
it)
Check: Make a check and print to the log all the data from 6 the arrays for every row before you set the data in the getView method.
getCount(), getItem() and getItemId() are not set properly.
getCount() should return the number of items in the arraylist;
getItem() should return the item at the given position from the arraylist;
getItemId() should return the internal id of the item if it has one, or the position of the item in the array or an hash number of the item.
I have a project which shows list of blood donors using place search, i want to insert a call button in that list view for each user, i have no idea how to add it, Can you please help me with this? Screenshot 1: Screenshot 2: Each detail of the blood donor like name , blood group and phone are stored in each field in the server. "bld_phn" is the id of text view that shows phone number."phone" is the array string
code:
public class blood extends Activity {
AsyncHttpClient client;
JSONArray jarray;
JSONObject jobject;
RequestParams params;
ListView lv;
EditText enter;
Button done;
Button call;
ArrayList<String> place;
ArrayList<String>incharge;
ArrayList<String>email;
ArrayList<String>phone;
ArrayList<String>reg;
ArrayList<String>Bld;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blood);
//prof=(EditText)findViewById(R.id.userProfile);
client = new AsyncHttpClient();
params = new RequestParams();
// submit=(Button)findViewById(R.id.submit);
lv = (ListView) findViewById(R.id.List_all_blood);
enter=(EditText)findViewById(R.id.enter_bld);
done=(Button)findViewById(R.id.enter_blood);
place = new ArrayList<String>();
incharge = new ArrayList<String>();
email = new ArrayList<String>();
phone = new ArrayList<String>();
reg = new ArrayList<String>();
Bld = new ArrayList<String>();
// final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl2);
// findViewById(R.id.rl1).setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(rl.getWindowToken(), 0);
//
// }
// });
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
place.clear();
incharge.clear();
email.clear();
phone.clear();
reg.clear();
String pl=enter.getText().toString();
params.put("place",pl);
client.get("http://srishti-systems.info/projects/accident/bloodsearch.php?", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
System.out.println(content + "jjjjj");
try {
jobject = new JSONObject(content);
Log.e(content, "hgsfdh");
String s = jobject.optString("Result");
Log.e(content,"dsfds");
if(s.equals("success")){
// SharedPreferences pref=getApplicationContext().getSharedPreferences("pref",MODE_PRIVATE);
// temp=pref.getString("user","");
// String a = jobject.optString("PoliceDetails");
jarray =jobject.getJSONArray("BloodDoner");
for (int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
String FN = obj.getString("firstname");
place.add("First Name :" + FN);
String LN = obj.getString("lastname");
incharge.add("Second Name :" + LN);
String mail = obj.getString("email");
email.add("Email :" + mail);
String ph = obj.getString("phone");
phone.add("Phone :" + ph);
String bd = obj.getString("bloodgrp");
Bld.add("BLood Group :" + bd);
}
}
else
Toast.makeText(getApplicationContext(),"No Donors Found",Toast.LENGTH_LONG).show();
adapter adpt = new adapter();
lv.setAdapter(adpt);
} catch (Exception e) {
}
}
});
}
});
}
public void hideKeyboard(View view) {
InputMethodManager imm =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class adapter extends BaseAdapter {
LayoutInflater Inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return place.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Inflater=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=Inflater.inflate(R.layout.blood_lst,null);
Viewholder holder=new adapter.Viewholder();
holder.pl=(TextView)convertView.findViewById(R.id.bld_name);
holder.pl.setText(place.get(position));
holder.in=(TextView)convertView.findViewById(R.id.bld_nm);
holder.in.setText(incharge.get(position));
holder.em=(TextView)convertView.findViewById(R.id.bld_em);
holder.em.setText(email.get(position));
holder.ph=(TextView)convertView.findViewById(R.id.bld_phn);
holder.ph.setText(phone.get(position));
holder.ph=(TextView)convertView.findViewById(R.id.bld_grp);
holder.ph.setText(Bld.get(position));
return convertView;
}
class Viewholder{
TextView pl;
TextView in;
TextView em;
TextView ph;
}
}
}
xml of the page :
<?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:id="#+id/rl2"
android:background="#9e9e9e">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/List_all_blood"
android:layout_below="#+id/enter_bld"
/>
<EditText
android:hint="enter place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_bld"
android:layout_weight="1"
android:layout_marginTop="49dp"
android:textColor="#000000"
android:textStyle="italic"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/enter_policebutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="done"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:textColor="#FFFFFF"
android:background="#3F51B5"
android:layout_marginRight="34dp"
android:layout_marginEnd="34dp"
android:id="#+id/enter_blood"
style="#style/Widget.AppCompat.Button"
android:layout_alignBaseline="#+id/enter_bld"
android:layout_alignBottom="#+id/enter_bld"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/enter_blood"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="11dp"
android:text="Blood Doners" />
</RelativeLayout>
xml of the list :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9e9e9e">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="25dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_name" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="30dp"
android:textSize="15dp"
android:textColor="#000000"
android:id="#+id/bld_nm"
android:layout_below="#+id/bld_name" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_em" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_phn" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_grp" />
</TableLayout>
For call button in listview you can add call button icon in listview's row file like below:-
<Button
android:id="#+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />
Then in activity, you can write below code in on click of call button to call functionality in android:-
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("phone number"));
startActivity(callIntent);
phone number in above code is a string var in which you can add number which you want to call.
I hope it will help you.
This is listview java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manager_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.list);
connectionClass = new ConnectionClass();
itemsArrayList = new ArrayList<ClassListItems>();
search = (EditText) findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
shp = this.getSharedPreferences("UserInfo", MODE_PRIVATE);
String userid = shp.getString("UserId", "none");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
TextView textViewUserId = (TextView) navigationView.getHeaderView(0).findViewById(R.id.textViewUserId);
textViewUserId.setText(userid);
}
private class SyncData extends AsyncTask<String, String, String> {
String msg = "Error";
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(ManagerDashboard.this, "Synchronising",
"Listview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
success = false;
} else {
String query = "SELECT * FROM dbo.Dashboard";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
if (rs.getString("AccountType").equals("Seller")) {
itemsArrayList.add(new ClassListItems(rs.getString("slsperid"), rs.getString("Visibility_Tgt"),
rs.getString("Visibility_Actual"), rs.getString("GPTgt"),
rs.getString("GPAct"), rs.getString("GSTgt"), rs.getString("GSAct")));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
Toast.makeText(ManagerDashboard.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemsArrayList, ManagerDashboard.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
Listview adapter
public class MyAppAdapter extends BaseAdapter {
public class ViewHolder{
TextView tvuserid, tvvstarget, tvvsact, tvvsp, tvgptarget, tvgpact, tvgpp, tvgstarget, tvgsact, tvgsp;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arrayList;
private MyAppAdapter(List<ClassListItems> apps, Context context){
this.parkingList = apps;
this.context = context;
arrayList = new ArrayList<ClassListItems>();
arrayList.addAll(parkingList);
}
#Override
public int getCount() {return parkingList.size();}
#Override
public Object getItem(int position) {return position;}
#Override
public long getItemId(int position) {return position;}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
View rowView = convertView;
ViewHolder viewHolder = null;
if(rowView == null){
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvuserid = (TextView) rowView.findViewById(R.id.tvuserid);
viewHolder.tvvstarget = (TextView) rowView.findViewById(R.id.tvvstarget);
viewHolder.tvvsact = (TextView) rowView.findViewById(R.id.tvvsact);
viewHolder.tvvsp = (TextView) rowView.findViewById(R.id.tvvsp);
viewHolder.tvgptarget = (TextView) rowView.findViewById(R.id.tvgptarget);
viewHolder.tvgpact = (TextView) rowView.findViewById(R.id.tvgpact);
viewHolder.tvgpp = (TextView) rowView.findViewById(R.id.tvgpp);
viewHolder.tvgstarget = (TextView) rowView.findViewById(R.id.tvgstarget);
viewHolder.tvgsact = (TextView) rowView.findViewById(R.id.tvgsact);
viewHolder.tvgsp = (TextView) rowView.findViewById(R.id.tvgsp);
rowView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvuserid.setText(parkingList.get(position).getName()+"");
viewHolder.tvvstarget.setText(parkingList.get(position).getVisibility_Tgt()+"");
viewHolder.tvvsact.setText(parkingList.get(position).getVisibility_Actual()+"");
viewHolder.tvuserid.setText(parkingList.get(position).getName()+"");
viewHolder.tvgptarget.setText(parkingList.get(position).getGPTgt()+"");
viewHolder.tvgpact.setText(parkingList.get(position).getGPAct()+"");
viewHolder.tvuserid.setText(parkingList.get(position).getName()+"");
viewHolder.tvgstarget.setText(parkingList.get(position).getGSTgt()+"");
viewHolder.tvgsact.setText(parkingList.get(position).getGSAct()+"");
Double value1 = Double.parseDouble(viewHolder.tvvstarget.getText().toString());
Double value2 = Double.parseDouble(viewHolder.tvvsact.getText().toString());
Double calculatedValue = (value2*100)/value1;
String formattedValue = String.format("%.2f", calculatedValue);
viewHolder.tvvsp.setText(formattedValue.toString()+"%");
Double value3 = Double.parseDouble(viewHolder.tvgptarget.getText().toString());
Double value4 = Double.parseDouble(viewHolder.tvgpact.getText().toString());
Double calculatedValue2 = (value4*100)/value3;
String formattedValue2 = String.format("%.2f", calculatedValue2);
viewHolder.tvgpp.setText(formattedValue2.toString()+"%");
Double value5 = Double.parseDouble(viewHolder.tvgstarget.getText().toString());
Double value6 = Double.parseDouble(viewHolder.tvgsact.getText().toString());
Double calculatedValue3 = (value6*100)/value5;
String formattedValue3 = String.format("%.2f", calculatedValue3);
viewHolder.tvgsp.setText(formattedValue3.toString()+"%");
return rowView;
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
parkingList.clear();
if(charText.length() == 0){
parkingList.addAll(arrayList);
} else {
for (ClassListItems apps: arrayList){
if (apps.getName().toLowerCase(Locale.getDefault()).contains(charText)){
parkingList.add(apps);
}
}
}
notifyDataSetChanged();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Intent myIntent = new Intent(ManagerDashboard.this,
ManagerActivity.class);
startActivity(myIntent);
} else if (id == R.id.nav_profile) {
Intent myIntent = new Intent(ManagerDashboard.this,
ManagerProfile.class);
startActivity(myIntent);
} else if (id == R.id.nav_dashboard) {
} else if (id == R.id.nav_logout) {
LogOut();
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void LogOut() {
SharedPreferences.Editor edit = shp.edit();
edit.putString("UserId", "");
edit.commit();
Intent intent = new Intent(ManagerDashboard.this, MainActivity.class);
startActivity(intent);
this.finish();
}
This is activity xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="170dp"
android:id="#+id/linearLayout1">
<TextView
android:layout_marginLeft="20dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:text="Seller"
android:textStyle="bold"
android:textColor="#000000"
android:textSize="15dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.23"
android:text="VS %"
android:textStyle="bold"
android:textColor="#000000"
android:textSize="15dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.18"
android:text="GP %"
android:textStyle="bold"
android:textColor="#000000"
android:textSize="15dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.18"
android:text="GS %"
android:textStyle="bold"
android:textColor="#000000"
android:textSize="15dp"/>
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
app:srcCompat="#drawable/logo" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:choiceMode="multipleChoice"
android:id="#+id/list"
android:layout_marginTop="210dp"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="170dp"
android:background="#android:color/darker_gray" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/linearLayout1"
android:background="#android:color/darker_gray" />
<EditText
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="95dp"
android:drawableRight="#drawable/search"
android:layout_marginLeft="150dp"
android:layout_marginRight="150dp"/>
This is listview xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/tvuserid"
android:layout_marginLeft="20dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:text="Seller"
android:textColor="#000000"
android:textSize="15dp"/>
<TextView
android:id="#+id/tvvsp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:text="VS %"
android:textColor="#000000"
android:textSize="15dp"/>
<TextView
android:id="#+id/tvgpp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:text="GP %"
android:textColor="#000000"
android:textSize="15dp"/>
<TextView
android:id="#+id/tvgsp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:text="GS %"
android:textColor="#000000"
android:textSize="15dp"/>
</LinearLayout>
<TextView
android:id="#+id/tvvstarget"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/tvvsact"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/tvgptarget"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/tvgpact"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/tvgstarget"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"/>
<TextView
android:id="#+id/tvgsact"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"/>
Why the listview got extra space? Even i chg the padding in xml file it wont change. It happen when i add much id in viewholder. That means if in viewholder only gt 4 id the listview did not have extra space in the bottom of every item. How to do the spacing divided equally? Anyone help pls. Thanks.
Change height of listView to wrap_content.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:choiceMode="multipleChoice"
android:id="#+id/list"
android:layout_marginTop="210dp"/>