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'.
Related
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
Very little experience when it comes to Java. My app pulls data from an API to a list view just fine. Once clicked on the list view I want to display more details. My code is in different files and I can't figure out how handle null results when I set my text view text. Right now it is giving me a few errors. Thank you in advanced. I've tried debugging and my own research to no avail for over a day.
My error was: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.
MainActivity.java:
public void showMemberDetailsScreen(int _id) {
mMembersListScreen.setVisibility(View.GONE);
mMemberDetailsScreen.setVisibility(View.VISIBLE);
if (NetworkUtils.isConnected(this)) {
GetDetailsTask task = new GetDetailsTask(this);
task.execute(_id);
} else {
Log.i(TAG, "onCreate: NOT CONNECTED");
}
}
/**
* Populate the member details screen with data.
*
* #param _name
* #param _birthday
* #param _gender
* #param _twitterId
* #param _numCommittees
* #param _numRoles
*/
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView)mMembersListScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}
OnItemClickListener mItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> _parent, View _view, int _position, long _id) {
// TODO: Show the members detail screen
Log.i(TAG, "onItemClick: RAN");
showMemberDetailsScreen(_position);
Log.i(TAG, "onItemClick: POSITION = " + _position);
}
};
GetDetailsTask.java:
private static final String NAME = "name";
private static final String BIRTHDAY = "birthday";
private static final String GENDER = "gender";
private static final String TWITTER_ID = "twitter_id";
private static final String NUM_COMMITTEES = "num_committees";
private static final String NUM_ROLES = "num_roles";
private MainActivity mActivity;
public GetDetailsTask(MainActivity _activity) {
mActivity = _activity;
}
#Override
protected HashMap<String, String> doInBackground(Integer... _params) {
// Add member ID to the end of the URL
String data = NetworkUtils.getNetworkData(API_URL + _params[0]);
HashMap<String, String> retValues = new HashMap<String, String>();
try {
JSONObject response = new JSONObject(data);
String name = response.optString("name");
retValues.put(NAME, name);
String birthday = response.optString("birthday");
retValues.put(BIRTHDAY, birthday);
String gender = response.optString("gender_label");
retValues.put(GENDER, gender);
String twitterId = response.optString("twitterid");
retValues.put(TWITTER_ID, twitterId);
if (response.has("committeeassignments")) {
JSONArray committeeArray = response.optJSONArray("committeeassignments");
int numCommittees = committeeArray.length();
retValues.put(NUM_COMMITTEES, "" + numCommittees);
Log.i(TAG, "doInBackground: NUM COMMITTESS = " + numCommittees);
} else {
retValues.put(NUM_COMMITTEES, "" + 0);
}
if (response.has("roles")){
JSONArray rolesArray = response.optJSONArray("roles");
int numRoles = rolesArray.length();
retValues.put(NUM_ROLES, "" + numRoles);
} else {
retValues.put(NUM_ROLES, "" + 0);
}
} catch(JSONException e) {
e.printStackTrace();
}
return retValues;
}
#Override
protected void onPostExecute(HashMap<String, String> _result) {
super.onPostExecute(_result);
if (_result != null) {
String name = _result.get(NAME);
String birthday = _result.get(BIRTHDAY);
String gender = _result.get(GENDER);
String twitterId = _result.get(TWITTER_ID);
String numCommittees = _result.get(NUM_COMMITTEES);
String numRoles = _result.get(NUM_ROLES);
mActivity.populateMemberDetailsScreen(name, birthday, gender, twitterId, numCommittees, numRoles);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/members_list_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<ListView
android:id="#+id/members_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/member_details_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/birthday" />
<TextView android:id="#+id/text_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/gender" />
<TextView
android:id="#+id/text_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/twitter_id" />
<TextView android:id="#+id/text_twitter_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/num_committees" />
<TextView
android:id="#+id/text_num_committees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_num_roles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
You are trying to show your details screen but in your method you are finding view by id under your mMembersListScreen when you should use mMemberDetailsScreen. Try this:
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}
guys I'm new in android programming and this is the second RecyclerView + cardview that I implement but I can't get what is wrong with this. The activity shows this:
Image from the blank activity instead the recyclerView
RecyclerView.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
android:id="#+id/rvPaquetes"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</android.support.v7.widget.RecyclerView>
CardView.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300sp"
android:layout_marginLeft="15sp"
android:layout_marginRight="15sp"
android:layout_marginTop="15sp"
android:id="#+id/cvPaquete"
android:background="#drawable/line_white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_blue"
android:padding="10dp" >
<ImageView
android:id="#+id/ivBox"
android:layout_marginTop="30sp"
android:layout_centerHorizontal="true"
android:layout_width="50sp"
android:layout_height="50sp"
android:src="#drawable/commercial_box"
android:cropToPadding="false"
/>
<TextView
android:id="#+id/tvCB"
android:layout_marginTop="15sp"
android:layout_marginLeft="40sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Codigo Barra: "
android:layout_below="#+id/ivBox"
android:textSize="16sp"
android:textColor="#color/white"
/>
<TextView
android:id="#+id/tvCBValue"
android:layout_marginTop="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1691028531"
android:layout_toRightOf="#+id/tvCB"
android:layout_below="#+id/ivBox"
android:textSize="16sp"
android:textColor="#color/white"
/>
<TextView
android:id="#+id/tvTracking"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tracking: "
android:layout_below="#+id/tvCB"
android:layout_marginLeft="40sp"
android:textColor="#color/white"
android:textSize="16sp"
/>
<TextView
android:id="#+id/tvTrackingValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1zwwe2155121"
android:layout_below="#+id/tvCB"
android:layout_toRightOf="#+id/tvTracking"
android:layout_marginLeft="30sp"
android:textColor="#color/white"
android:textSize="16sp"
/>
<TextView
android:id="#+id/tvRemitente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remitente: "
android:layout_below="#+id/tvTracking"
android:layout_marginLeft="40sp"
android:textColor="#color/white"
android:textSize="16sp"
/>
<TextView
android:id="#+id/tvRemitenteValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conrado Rivera"
android:layout_below="#+id/tvTracking"
android:layout_toRightOf="#+id/tvRemitente"
android:layout_marginLeft="30sp"
android:textColor="#color/white"
android:textSize="16sp"
/>
<TextView
android:id="#+id/tvConsignatario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Consignatario: "
android:layout_below="#+id/tvRemitente"
android:layout_marginLeft="40sp"
android:textColor="#color/white"
android:textSize="16sp"
/>
<TextView
android:id="#+id/tvConsignatarioValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AMAZON"
android:layout_below="#+id/tvRemitente"
android:layout_toRightOf="#+id/tvConsignatario"
android:textColor="#color/white"
android:textSize="16sp"
/>
<TextView
android:id="#+id/tvFechaEnvio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fecha de envio: "
android:textColor="#color/white"
android:textSize="16sp"
android:layout_marginLeft="40sp"
android:layout_below="#+id/tvConsignatario"
/>
<TextView
android:id="#+id/tvFechaEnvioValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="01/07/2016"
android:textColor="#color/white"
android:textSize="16sp"
android:layout_toRightOf="#+id/tvFechaEnvio"
android:layout_below="#+id/tvConsignatario"
/>
<TextView
android:id="#+id/tvNumeroPiezas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No. Piezas: "
android:textColor="#color/white"
android:textSize="16sp"
android:layout_below="#+id/tvFechaEnvio"
android:layout_marginLeft="40sp"
/>
<TextView
android:id="#+id/tvNumeroPiezasValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:textColor="#color/white"
android:textSize="16sp"
android:layout_below="#+id/tvFechaEnvio"
android:layout_toRightOf="#+id/tvNumeroPiezas"
/>
<TextView
android:id="#+id/tvPeso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Peso: "
android:textColor="#color/white"
android:textSize="16sp"
android:layout_below="#+id/tvNumeroPiezas"
android:layout_marginLeft="40sp"
/>
<TextView
android:id="#+id/tvPesoValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:textColor="#color/white"
android:textSize="16sp"
android:layout_below="#+id/tvNumeroPiezas"
android:layout_toRightOf="#+id/tvPeso"
/>
<TextView
android:id="#+id/tvValorDeclarado"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valor declarado: "
android:textColor="#color/white"
android:textSize="16sp"
android:layout_below="#+id/tvPeso"
android:layout_marginLeft="40sp"
/>
<TextView
android:id="#+id/tvValorDeclaradoValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="350.00"
android:textColor="#color/white"
android:textSize="16sp"
android:layout_below="#+id/tvPeso"
android:layout_toRightOf="#+id/tvValorDeclarado"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
MainActivity.class
public class ExportacionesRastreoPaqueteActivity extends AppCompatActivity {
private ArrayList<Paquete> paquetes;
private RecyclerView listaPaquetes;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_exportaciones_rastreo_paquete);
listaPaquetes = (RecyclerView) findViewById(R.id.rvPaquetes);
listaPaquetes.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
listaPaquetes.setLayoutManager(llm);
inicializarListaPaquetes();
inicializarAdaptador();
}
public void inicializarAdaptador(){
RVAdapterPaquete adaptador = new RVAdapterPaquete(paquetes);
listaPaquetes.setAdapter(adaptador);
}
public void inicializarListaPaquetes(){
paquetes = new ArrayList<Paquete>();
paquetes.add(new Paquete("CB111111","TK222222", "Amazon", "Conrado", "13/10/2013", "2", "2", "3.16"));
paquetes.add(new Paquete("CB111222","TK222222", "Amazon", "Conrado", "13/10/2013", "2", "2", "3.16"));
paquetes.add(new Paquete("CB113333","TK222222", "Amazon", "Conrado", "13/10/2013", "2", "2", "3.16"));
paquetes.add(new Paquete("CB114444","TK222222", "Amazon", "Conrado", "13/10/2013", "2", "2", "3.16"));
}}
Adapter
public class RVAdapterPaquete extends RecyclerView.Adapter{
public RVAdapterPaquete(ArrayList paquetes) {
this.paquetes = paquetes;
}
ArrayList<Paquete> paquetes;
#Override
public PaqueteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //Inflar o darle vida a nuestro layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_rastreo_resutados, parent, false);
return new PaqueteViewHolder(v);
}
#Override
public void onBindViewHolder(PaqueteViewHolder paqueteViewHolder, int position) {
//Asocia cada elemento de la lista con cada view
Paquete paquete = paquetes.get(position);
paqueteViewHolder.tvCB.setText(paquete.getCodigoBarra());
paqueteViewHolder.tvTracking.setText(paquete.getTracking());
paqueteViewHolder.tvRemitente.setText(paquete.getRemitente());
paqueteViewHolder.tvConsignatario.setText(paquete.getConsignatario());
paqueteViewHolder.tvFechaEnvio.setText(paquete.getFechaEnvio());
//paqueteViewHolder.tvContenido.setText(paquete.getContenido());
paqueteViewHolder.tvNumeroPiezas.setText(paquete.getPiezas());
paqueteViewHolder.tvPeso.setText(paquete.getPeso());
paqueteViewHolder.tvValorDeclarado.setText(paquete.getValorDeclarado());
}
#Override
public int getItemCount() { //Cantidad de elementos que contiene mi lista.
return paquetes.size();
}
public static class PaqueteViewHolder extends RecyclerView.ViewHolder{
//Obtiene las partes del xml a llenar
private TextView tvCB;
private TextView tvTracking;
private TextView tvRemitente;
private TextView tvConsignatario;
private TextView tvFechaEnvio;
//private TextView tvContenido;
private TextView tvNumeroPiezas;
private TextView tvPeso;
private TextView tvValorDeclarado;
public PaqueteViewHolder(View itemView) {
super(itemView);
tvCB = (TextView) itemView.findViewById(R.id.tvCBValue);
tvTracking = (TextView) itemView.findViewById(R.id.tvTrackingValue);
tvRemitente = (TextView) itemView.findViewById(R.id.tvRemitenteValue);
tvConsignatario = (TextView) itemView.findViewById(R.id.tvConsignatarioValue);
tvFechaEnvio = (TextView) itemView.findViewById(R.id.tvFechaEnvioValue);
// tvContenido = (TextView) itemView.findViewById(R.id.tvContenidoValue);
tvNumeroPiezas = (TextView) itemView.findViewById(R.id.tvNumeroPiezasValue);
tvPeso = (TextView) itemView.findViewById(R.id.tvPesoValue);
tvValorDeclarado = (TextView) itemView.findViewById(R.id.tvValorDeclaradoValue);
}
}
}
Data class
public class Paquete {
private String codigoBarra;
private String Tracking;
private String remitente;
private String consignatario;
private String fechaEnvio;
private String piezas;
private String peso;
private String valorDeclarado;
private String imgRecibida;
public Paquete() {
}
public Paquete(String codigoBarra, String tracking, String remitente, String consignatario, String fechaEnvio, String piezas, String peso, String valorDeclarado) {
this.codigoBarra = codigoBarra;
Tracking = tracking;
this.remitente = remitente;
this.consignatario = consignatario;
this.fechaEnvio = fechaEnvio;
this.piezas = piezas;
this.peso = peso;
this.valorDeclarado = valorDeclarado;
}
public String getCodigoBarra() {
return codigoBarra;
}
public void setCodigoBarra(String codigoBarra) {
this.codigoBarra = codigoBarra;
}
public String getTracking() {
return Tracking;
}
public void setTracking(String tracking) {
Tracking = tracking;
}
public String getRemitente() {
return remitente;
}
public void setRemitente(String remitente) {
this.remitente = remitente;
}
public String getConsignatario() {
return consignatario;
}
public void setConsignatario(String consignatario) {
this.consignatario = consignatario;
}
public String getFechaEnvio() {
return fechaEnvio;
}
public void setFechaEnvio(String fechaEnvio) {
this.fechaEnvio = fechaEnvio;
}
public String getPiezas() {
return piezas;
}
public void setPiezas(String piezas) {
this.piezas = piezas;
}
public String getPeso() {
return peso;
}
public void setPeso(String peso) {
this.peso = peso;
}
public String getValorDeclarado() {
return valorDeclarado;
}
public void setValorDeclarado(String valorDeclarado) {
this.valorDeclarado = valorDeclarado;
}
public String getImgRecibida() {
return imgRecibida;
}
public void setImgRecibida(String imgRecibida) {
this.imgRecibida = imgRecibida;
}
}
You need to call notifyDataSetChanged(); when set the adapter to reclyclerView like this:
public void inicializarAdaptador(){
RVAdapterPaquete adaptador = new RVAdapterPaquete(paquetes);
listaPaquetes.setAdapter(adaptador);
notifyDataSetChanged();
}
Otherwise the recycler will not realize that you have setted new data.
In your custom adapter class, set the layout being inflated to that of the card view.xml. I.e.
public PaqueteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //Inflar o darle vida a nuestro layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview.xml, parent, false);
return new PaqueteViewHolder(v);
}
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.
I wanted to do a view output using table layout.
My idea goes like this.
I have a main page, known as activity_main.xml
when you click on the cancel button, it will go to a summary page,
know as data.xml.
In data.xml, I have a date edittext, whereby ,when I enter a date,eg 12/2/2013,
and after I click the button search, it will show me the record of it.
However, I'm not sure how to do it.
If I didn't enter any date and click "search", it will show all the records.
Right now,I am able to show all the records, without searching the data.
Below is my code.
Can someone kindly help me out with the search by date?
I hope that I've explained myself clear enough.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_PRICE = "fuelprice";
public static final String KEY_FUEL = "fuelpump";
public static final String KEY_COST = "tcost";
public static final String KEY_ODM = "odometer";
public static final String KEY_CON = "fcon";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "fuelLog";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}//onCreate
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}//onUpgrade
}//DatabaseHelper
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//open
//---closes the database---
public void close()
{
DBHelper.close();
}//close
//---insert a log into the database---
public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_PRICE, fuelprice);
initialValues.put(KEY_FUEL, fuelpump);
initialValues.put(KEY_COST, tcost);
initialValues.put(KEY_ODM, odometer);
initialValues.put(KEY_CON, fcon);
return db.insert(DATABASE_TABLE, null, initialValues);
}//insertLog
// --retrieves all the data
public Cursor getAllLog()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE, KEY_PRICE, KEY_FUEL,KEY_ODM,KEY_CON}, null, null, null, null, null);
}
}
summary.java
public class summary extends Activity{
TableLayout tablelayout_Log = null;
Button searchButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
tablelayout_Log = (TableLayout) findViewById(R.id.tableLayout_Log);
tablelayout_Log.setStretchAllColumns(true);
tablelayout_Log.setShrinkAllColumns(true);
//View
searchButton = (Button) findViewById(R.id.searchBtn);
searchButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
}
});
}//oncreate
public void refreshTable()
{
tablelayout_Log.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Fuel Log");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span = 5;
rowTitle.addView(title, params);
tablelayout_Log.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try
{
dbAdaptor.open();
cursor = dbAdaptor.getAllLog();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String date = cursor.getString(1);
String price = cursor.getString(2);
String pump = cursor.getString(3);
String odometer = cursor.getString(4);
String fcon = cursor.getString(5);
TextView viewId = new TextView(getApplicationContext());
viewId.setText("" + id);
TextView viewDate = new TextView(getApplicationContext());
viewDate.setText(date);
TextView viewPrice = new TextView(getApplicationContext());
viewPrice.setText(price);
TextView viewPump = new TextView(getApplicationContext());
viewPump.setText(pump);
TextView viewOdometer = new TextView(getApplicationContext());
viewOdometer.setText(odometer);
TextView viewCon = new TextView(getApplicationContext());
viewCon.setText(fcon);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(viewId);
row.addView(viewDate);
row.addView(viewPrice);
row.addView(viewPump);
row.addView(viewOdometer);
row.addView(viewCon);
tablelayout_Log.addView(row);
}
while(cursor.moveToNext());
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}//refreshTable
}//main
MainActivity.java
public class MainActivity extends Activity {
TableLayout tablelayout_Contacts = null;
Button insertButton = null;
EditText nameEdit = null;
EditText contactEdit = null;
Button viewButton = null;
Button deleteButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablelayout_Contacts = (TableLayout) findViewById(R.id.tableLayout_Contacts);
tablelayout_Contacts.setStretchAllColumns(true);
tablelayout_Contacts.setShrinkAllColumns(true);
nameEdit = (EditText) findViewById(R.id.editText_Name);
contactEdit = (EditText) findViewById(R.id.editText_Number);
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
dbAdaptor.open();
String name = nameEdit.getText().toString();
String number = contactEdit.getText().toString();
dbAdaptor.insertContact(name, number);
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
finally{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
//View records
viewButton = (Button) findViewById(R.id.button2);
viewButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
//delete records
deleteButton = (Button) findViewById(R.id.button3);
deleteButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
refreshTable();
String name = nameEdit.getText().toString();
if(!name.equals(""))
{
dbAdaptor.deleteContact(name);
}
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
}//oncreate
//refresh table
public void refreshTable()
{
tablelayout_Contacts.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Contacts");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span =3;
rowTitle.addView(title,params);
tablelayout_Contacts.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try{
dbAdaptor.open();
cursor = dbAdaptor.getAllContacts();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String name = cursor.getString(1);
String contact = cursor.getString(2);
TextView idView = new TextView(getApplicationContext());
idView.setText("" + id);
TextView nameView = new TextView(getApplicationContext());
nameView.setText(name);
TextView contactView = new TextView(getApplicationContext());
nameView.setText(contact);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(idView);
row.addView(nameView);
row.addView(contactView);
tablelayout_Contacts.addView(row);
}
while (cursor.moveToNext());
}
catch (Exception e)
{
Log.d("Contact Manager", e.getMessage());
}
finally{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/updateBTN"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/datepast"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fc"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/highpricetxtview"
android:text="#string/highprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/highprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/searchBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search" />
<Button
android:id="#+id/deleteBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<Button
android:id="#+id/backBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout_Log"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
The error you are getting is a nullpointer that means that some object that is at line 205 in MainActivity or it is used at that line is null. Check that first and then try to run again.
The immediate problem is here:
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
Not all throwables have a message and a null can be returned. A null cannot be logged. It causes the "println needs a message" exception in the stacktrace.
So first, change that to e.g.
catch (Exception e)
{
Log.e("Fuel Log", "", e);
}
This will log the exception with error level, empty message and with full stacktrace.
Then you can see what causes that exception in the first place.
Hello date type is not supported in Sqlite Database.you have assign date as text so it will take string so you need to keep string in proper order so that it can work as date search.
You can store date in form of 2013-12-23 (20131223) then you can get your query by passing date
by the way you can try like below
public ArrayList<String> getEventsForNotification(String dateSearch)
{
ArrayList<String> arrayList=new ArrayList<String>();
String sql="SELECT "+KEY_EVENT_NAME+" FROM "+ TABLE_EVENT +" WHERE SUBSTR("+KEY_EVENT_DATE+",6) like '"+dateSearch+"'";
Cursor cursor=sqLiteDatabase.rawQuery(sql, null);
if(cursor.moveToFirst())
{
do
{
arrayList.add(cursor.getString(0));
}while(cursor.moveToNext());
cursor.close();
cursor=null;
}
return arrayList;
}
modify according to your need.