As the title says, I need to get the value of an editText contained in a fragment activity, being part of a ViewPager; I've tried everything so far, and I've understood that the xml items can be accessed just by passing the current view of the activity after inflating it, and that's what i've done.. But i need to have the values contained in the edittexts after the user fills it, specifically after a button 'save' is pressed; during the execution of the program i get this error when i try to get the text contained: "java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference"
Sorry for the silly question, i'm new to android programming and i appreciate all the help i can get
Here's the code of the fragment activity:
public class Monday extends android.support.v4.app.Fragment{
EditText[] subjects = new EditText[6];
EditText[] classes = new EditText[6];
private OnFragmentInteractionListener mListener;
public Monday() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ScrollView scrollView = (ScrollView)inflater.inflate(R.layout.fragment_monday, container, false);
//some code
subjects[0] = (EditText) scrollView.findViewById(R.id.editTextMateria1);
subjects[1] = (EditText) scrollView.findViewById(R.id.editTextMateria2);
subjects[2] = (EditText) scrollView.findViewById(R.id.editTextMateria3);
subjects[3] = (EditText) scrollView.findViewById(R.id.editTextMateria4);
subjects[4] = (EditText) scrollView.findViewById(R.id.editTextMateria5);
subjects[5] = (EditText) scrollView.findViewById(R.id.editTextMateria6);
classes[0] = (EditText) scrollView.findViewById(R.id.editTextClasse1);
classes[1] = (EditText) scrollView.findViewById(R.id.editTextClasse2);
classes[2] = (EditText) scrollView.findViewById(R.id.editTextClasse3);
classes[3] = (EditText) scrollView.findViewById(R.id.editTextClasse4);
classes[4] = (EditText) scrollView.findViewById(R.id.editTextClasse5);
classes[5] = (EditText) scrollView.findViewById(R.id.editTextClasse6);
return scrollView;
//return inflater.inflate(R.layout.fragment_monday, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public String[] calculateDay(){
String s = "";
for(int i=1;i<subjects.length;i++){
s += subjects[i].getText().toString()+"-"+classes[i].getText().toString()+";";
}
String[] monday = new String[6];
monday = s.split(";");
return monday;
}
}
That's the part that generates the error:
s += subjects[i].getText().toString()+"-"+classes[i].getText().toString()+";";
Here's the code of the 'mainactivity' that generates the ViewPager(on which the button pressed save is handled):
public class CustomTimetables extends FragmentActivity implements NoticeDialogFragment.NoticeDialogListener{
public static String classname = "";
ViewPager viewPager = null;
private MyAdapter2 mAdapter;
ViewPager Tab;
MyAdapter2 TabAdapter;
ActionBar actionBar;
PagerSlidingTabStrip tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_custom_timetables);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
Tab = (ViewPager) findViewById(R.id.pager);
TabAdapter = new MyAdapter2(getSupportFragmentManager());
Tab.setAdapter(TabAdapter);
tabs.setViewPager(Tab);
Toast.makeText( getApplicationContext(),
"Inserisci l'orario nelle caselle, lasciale vuote se le lezioni terminano prima ",
Toast.LENGTH_LONG
).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_custom_timetables, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSaveTimetable(View v){
DialogFragment dialog = new NoticeDialogFragment();
dialog.show(this.getSupportFragmentManager(), "insert_class");
}
public void onDialogPositiveClick(DialogFragment dialog) {
String timetable = "Orario;Lunedi;Martedi;Mercoledi;Giovedi;Venerdi;Sabato;\n08:00;";
String[] monday = new String[6];
Monday m = new Monday();
monday = m.calculateDay();
for(int i = 0; i<6; i++){
timetable += monday[i]+";";
switch(i){
case 0: timetable +="\n";break;
case 1 : timetable +="\n09:00;";break;
case 2 : timetable +="\n10:00;";break;
case 3 : timetable +="\n11:05;";break;
case 4 : timetable +="\n12:00;";break;
case 5 : timetable +="\n12:50;";break;
}
}
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
}
}
class MyAdapter2 extends FragmentStatePagerAdapter
{
public MyAdapter2(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0){
fragment = new Monday();
}
if(i==1){
fragment = new Tuesday();
}
if(i==2){
fragment = new Wednesday();
}
if(i==3){
fragment = new Thursday();
}
if(i==4){
fragment = new Friday();
}
if(i==5){
fragment = new Saturday();
}
return fragment;
}
#Override
public int getCount() {
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Lunedi";
}
if(position == 1){
return "Martedi";
}
if(position == 2){
return "Mercoledi";
}
if(position == 3){
return "Giovedi";
}
if(position == 4){
return "Venerdi";
}
if(position == 5){
return "Sabato";
}
return null;
}
}
Here's the logcat:
06-09 19:29:16.172 24414-24443/com.progettostage.nick__000.timetablesapp D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-09 19:29:16.187 24414-24414/com.progettostage.nick__000.timetablesapp D/Atlas﹕ Validating map...
06-09 19:29:16.250 24414-24443/com.progettostage.nick__000.timetablesapp I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 01/15/15, ab0075f, Id3510ff6dc
06-09 19:29:16.252 24414-24443/com.progettostage.nick__000.timetablesapp I/OpenGLRenderer﹕ Initialized EGL, version 1.4
06-09 19:29:16.290 24414-24443/com.progettostage.nick__000.timetablesapp D/OpenGLRenderer﹕ Enabling debug mode 0
06-09 19:32:20.725 24414-24443/com.progettostage.nick__000.timetablesapp V/RenderScript﹕ Application requested CPU execution
06-09 19:32:20.738 24414-24443/com.progettostage.nick__000.timetablesapp V/RenderScript﹕ 0xb83ba0b8 Launching thread(s), CPUs 4
06-09 19:32:38.415 24414-24414/com.progettostage.nick__000.timetablesapp D/AndroidRuntime﹕ Shutting down VM
06-09 19:32:38.422 24414-24414/com.progettostage.nick__000.timetablesapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.progettostage.nick__000.timetablesapp, PID: 24414
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.progettostage.nick__000.timetablesapp.Monday.calculateDay(Monday.java:111)
at com.progettostage.nick__000.timetablesapp.CustomTimetables.onDialogPositiveClick(CustomTimetables.java:111)
at com.progettostage.nick__000.timetablesapp.NoticeDialogFragment$2.onClick(NoticeDialogFragment.java:33)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And this is simply the class that handles the dialog, i dont think it has anything to do with it, but better safe than sorry..
public class NoticeDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_classinput, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view)
// Add action buttons
.setTitle("Inserisci nome classe")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
EditText et = (EditText)view.findViewById(R.id.classname22);
CustomTimetables.classname = et.getText().toString();
// Send the positive button event back to the host activity
mListener.onDialogPositiveClick(NoticeDialogFragment.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
return builder.create();
}
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
}
Here's the Monday.xml as well(had to cut off some parts in the end cause it was too long, but it's simple, it goes on like this till editTextMateria6 and editTextClasse6):
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Monday"
>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="58dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="8:00-9:00"
android:id="#+id/PrimaOra"
android:textSize="25dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Materia"
android:id="#+id/materia1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="115dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextMateria1"
android:layout_marginTop="160dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Classe"
android:id="#+id/classe1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="225dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextClasse1"
android:layout_marginTop="270dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
-----------------------------------------------------
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="58dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="9:00-10:00"
android:id="#+id/SecondaOra"
android:textSize="25dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="325dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Materia"
android:id="#+id/materia2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="390dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextMateria2"
android:layout_marginTop="435dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Classe"
android:id="#+id/classe2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="500dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextClasse2"
android:layout_marginTop="545dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
-----------------------------------------
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="58dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="10:00-10:50"
android:id="#+id/TerzaOra"
android:textSize="25dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="600dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Materia"
android:id="#+id/materia3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="665dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextMateria3"
android:layout_marginTop="710dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Classe"
android:id="#+id/classe3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="775dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextClasse3"
android:layout_marginTop="825dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
-----------------------------------------
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="58dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="11:05-12:00"
android:id="#+id/QuartaOra"
android:textSize="25dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="875dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Materia"
android:id="#+id/materia4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="940dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextMateria4"
android:layout_marginTop="985dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Classe"
android:id="#+id/classe4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="1050dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextClasse4"
android:layout_marginTop="1095dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
------------------------------------------------
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="58dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="12:00-12:50"
android:id="#+id/QuintaOra"
android:textSize="25dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="1150dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Materia"
android:id="#+id/materia5"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="1215dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextMateria5"
android:layout_marginTop="1260dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Classe"
android:id="#+id/classe5"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="1325dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/editTextClasse5"
android:layout_marginTop="1380dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
----------------------------------------------
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="58dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="12:50-13:40"
android:id="#+id/SestaOra"
android:textSize="25dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="1435dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Materia"
android:id="#+id/materia6"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="1500dp" />
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:width="400dp"
android:height="70dp"
android:onClick="onSaveTimetable"
android:text="Salva"
android:layout_marginTop="1700dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
</ScrollView>
UPDATE
Okay I've added a few lines so maybe it is more clear what the problem is..
String sub1 = subjects[0].getText().toString();
String classr1 = classes[0].getText().toString();
for(int i=0;i<subjects.length;i++){
s += subjects[i].getText().toString()+"-"+classes[i].getText().toString()+";";
}
If I set it like this, I get the same exact error right at the sub1 line, because in a method like this one i'm not able to pass the view or inflate that, as I did on oncreateview, where it works just fine whatever operation I do.. The problem is that I need those edittext after the user had put something inside them.. I hope i've been a little clearer, I appreciate all the help I'm still getting and I'd like to point out that I've tried every single solution down here, even tho I didn't reply to them all
Array index starts from 0. Please make sure you use correct index values when accessing arrays.
This is wrong usage:
Monday m = new Monday();
monday = m.calculateDay();
Try this:
Monday m = mAdapter.getItem(viewPager.getCurrentItem());
monday = m.calculateDay();
It has been said before, but I'll say it again.
for(int i=1;i<7;i++){
s += subjects[i].getText().toString()+"-"+classes[i].getText().toString()+";";
Should be
for(int i = 0; i < subjects.length; i++){
s += subjects[i].getText().toString()+"-"+classes[i].getText().toString()+";";
EDIT: To be honest, I'd just write the code like this instead
public enum Days {
MONDAY("Lunedi") { //should be string resource
public Fragment createFragment() {
return new Monday();
}
},
TUESDAY("Martedi") {
public Fragment createFragment() {
return new Tuesday();
}
},
WEDNESDAY("Mercoledi") {
public Fragment createFragment() {
return new Wednesday();
}
},
THURSDAY("Giovedi") {
public Fragment createFragment() {
return new Thursday();
}
},
FRIDAY("Venerdi") {
public Fragment createFragment() {
return new Friday();
}
},
SATURDAY("Sabato") {
public Fragment createFragment() {
return new Saturday();
}
};
private String name;
private Days(String name) {
this.name = name;
}
public String getName() { return name; }
public abstract Fragment createFragment();
}
class MyAdapter2 extends FragmentStatePagerAdapter
{
public MyAdapter2(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
Days[] days = Days.values();
if(i < days.length) {
fragment = days[i].createFragment();
}
return fragment;
}
#Override
public int getCount() {
return Days.values().length;
}
#Override
public CharSequence getPageTitle(int position) {
Days[] days = Days.values();
if(position < days.length) {
return days[position].getName();
} else {
return null;
}
}
}
And to be fair, and most importantly, subjects[5] = (EditText) scrollView.findViewById(R.id.editTextMateria6); is null because editTextMateria6 does not exist in fragment_monday.xml, and neither does editTextClasse6.
You can maybe try using the :
getSupportFragmentManager().findFragmentById
to get hold of the already initiated Monday fragment in your onDialogPositiveClick. You can then use this fragment to invoke the calculateDay method. An id can be set in the xml file for the fragment. Your current implementation to create an instance and invoke calculateDay is incorrect.
In the xml layout of your Activity where I am assuming you've added the fragment tag, add an id attribute. Then in your onDialogPositiveClick, call
Monday monday = (Monday) getSupportFragmentManager().
findFragmentById("that fragment id here");
Now, use this monday variable to invoke the calculateDay method.
Some official documentation: http://developer.android.com/training/basics/fragments/communicating.html#Deliver
Related
hello guys i'm back again on a question conserning my final project.
i have made a googlemap app with navigation drawer using activity( no fragment). i think you know about that. then rather than using header and menu, i have use a layout where the header should be so that i can make there a listview to display events all of this is clear.
screenshot
MapActivity :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
DrawerLayout drawerLayout;
LinearLayout drawer_up;
FloatingActionsMenu mainfloating;
FloatingActionButton profile, evennement, historique,reglage,aidesupport;
ImageButton zoomin,zoomout,showtail,zoom_auto,showgeofence,maplayer,drawermenugroit,drawermenugauche;
ProgressDialog progressDialog;
private Dialog mDialog;
private GoogleMap map;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
RelativeLayout nodata_layout;
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
ImageButton map_layer_icon;
private AsyncTask downloadingAsync;
#Bind(R.id.listevent)
ListView listevent;
#Bind(R.id.clearAllEvents)
Button clearAllEvents;
#Bind(R.id.list) ListView list;
#Bind(R.id.nodata_layout) RelativeLayout nodata_layout1;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
Boolean isAllFabsVisible;
RelativeLayout content_layout;
//fin de declaration a garder en tete
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
setContentView(R.layout.activity_map);
//devices elements
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
final String api_key = (String) DataSaver.getInstance(MapActivity.this).load("api_key");
final EventsAdapter adapter = new EventsAdapter(this);
listevent.setAdapter(adapter);
//deviceIdSmallMarkerInfo = new HashMap<>();
//delaration des boutons pour le compte de floatingButton, etc...;
drawermenugroit = findViewById(R.id.drawermenudroit);
drawer_up = findViewById(R.id.drawerup);
drawermenugauche = findViewById(R.id.drawermenugauche);
drawerLayout = findViewById(R.id.drawer);
// profile = findViewById(R.id.profile);
mainfloating = findViewById(R.id.mainFloatingBtn);
evennement = findViewById(R.id.evennements);
historique = findViewById(R.id.historiques);
reglage = findViewById(R.id.reglages);
aidesupport = findViewById(R.id.aide_support);
zoomin = findViewById(R.id.zoom_in);
LinearLayout list_event = findViewById(R.id.list_event);
zoomout = findViewById(R.id.zoom_out);
showtail = findViewById(R.id.showtails);
zoom_auto = findViewById(R.id.autozoom);
listevent = (ListView) findViewById(R.id.listevent);
list = (ListView) findViewById(R.id.list);
showgeofence = findViewById(R.id.geofences);
maplayer = findViewById(R.id.map_layer);
map_layer_icon = (ImageButton) findViewById(R.id.map_layer);
//loading_bar = (ProgressBar) findViewById(R.id.loading_progBar);
content_layout = (RelativeLayout) findViewById(R.id.content_layout);
nodata_layout = (RelativeLayout) findViewById(R.id.nodata_layout);
//fin de declaration de boutons
//chargement des données
progressDialog = new ProgressDialog(this);
progressDialog = new ProgressDialog(MapActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Chargement de la carte"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
// fni de chargement des données
//open drawer and load list data in drawer layout button
drawermenugauche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDrawer(drawerLayout);
API.getApiInterface(MapActivity.this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
#Override
public void success(ApiInterface.GetEventsResult result, Response response) {
adapter.setArray(result.items.data);
if(result.items.data.size() != 0)
listevent.setVisibility(View.VISIBLE);
else
nodata_layout1.setVisibility(View.VISIBLE);
listevent.setVisibility(View.GONE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
});
drawer_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeDrawer(drawerLayout);
}
});
zoomin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomIn());
}
});
zoomout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomOut());
}
});
zoom_auto.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
isAutoZoomEnabled = !isAutoZoomEnabled;
if (isAutoZoomEnabled)
{
zoom_auto.setImageResource(R.drawable.icon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Activé", Toast.LENGTH_SHORT).show();
} else
{
zoom_auto.setImageResource(R.drawable.disableicon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Désactivé", Toast.LENGTH_SHORT).show();
}
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// ouverture et fermeture de drawer
private static void openDrawer(DrawerLayout drawerLayout){
drawerLayout.openDrawer(GravityCompat.START);
}
private static void closeDrawer(DrawerLayout drawerLayout){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
//fin ouverture et fermeture drawer
......etc...
see my EventsAdapter code below:
public class EventsAdapter extends AwesomeAdapter<Event> {
public EventsAdapter(Context context) {
super(context);
}
ArrayList<Event> original;
#Override
public void setArray(ArrayList<Event> array) {
super.setArray(array);
if(original == null)
original = array;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
Event item = getItem(position);
TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
device_name.setText(item.device_name);
TextView date = (TextView) convertView.findViewById(R.id.date);
date.setText(item.time);
TextView message = (TextView) convertView.findViewById(R.id.message);
message.setText(item.message);
TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
geofence_name.setText(item.geofence_name);
return convertView;
}
ItemFilter mFilter = new ItemFilter();
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 ArrayList<Event> nlist = new ArrayList<>();
for(Event item : original)
{
if(item.fitForFilter(filterString))
nlist.add(item);
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
setArray((ArrayList<Event>) results.values);
notifyDataSetChanged();
}
}
}
then in my adapter_event layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/whitesplash"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/instance"
android:layout_width="16dp"
android:layout_height="22dp"
android:src="#drawable/custom_floating_button" />
<TextView
android:id="#+id/device_nam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="Info Balise"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/device_nam"
android:outlineAmbientShadowColor="#color/blue" />
<TextView
android:id="#+id/device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_nam"
android:layout_marginStart="16dp"
android:fontFamily="#font/fjallaoneregular"
android:text="device name"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/textspeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_nam"
android:fontFamily="#font/fjallaoneregular"
android:text="Vitesse"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_name"
android:fontFamily="#font/fjallaoneregular"
android:text="speed"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/message1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_toRightOf="#+id/textspeed"
android:fontFamily="#font/fjallaoneregular"
android:text="message"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/speed"
android:fontFamily="#font/fjallaoneregular"
android:text="massage"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<View
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name" />
<TextView
android:id="#+id/datetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="date:"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/datetext"
android:fontFamily="#font/fjallaoneregular"
android:text="date"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<TextView
android:id="#+id/geofence_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="geofence_name"
android:fontFamily="#font/lobsterregular"
android:layout_below="#+id/date"
android:layout_marginStart="3dp"
android:layout_toRightOf="#+id/instance"
android:textSize="8dp"
android:textColor="#color/blue"/>
</RelativeLayout>
in this adpater_events i have found no mistake. and in the drawer_tracesas i said before( i am not using menu and header in navigationDrawer i would like to use a layout that i called drawer_traces) like below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/drawerup"
android:orientation="horizontal"
android:background="#color/blue">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/objects"
android:src="#drawable/ic_menu_24"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:text="#string/objects" />
</LinearLayout>
<TextView
android:id="#+id/Liste_Balises"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/drawerup"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_balises"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_balises"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:layout_below="#+id/Liste_Balises"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<TextView
android:id="#+id/list_events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_balises"
android:layout_marginTop="10dp"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_evennemT"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_event"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#+id/list_events"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/listevent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<RelativeLayout
android:id="#+id/nodata_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/list_event"
android:layout_above="#+id/clearAllEvents"
android:background="#ffffff"
android:visibility="gone"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/noEventsData"/>
</RelativeLayout>
<Button
android:id="#+id/clearAllEvents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_event"
android:fontFamily="#font/fjallaoneregular"
android:text="Effacer Evennements"/>
</RelativeLayout>
this layout (drawer_trace) will be displayed in mapActivity as a navigation Drawer. we are ok for that.
and then i have my Events Model:
public class Event
{
public int id, user_id, device_id, position_id, alert_id;
// geofence_id
public String message;
public String address;
public float altitude;
// course
public float latitude, longitude;
// power
public float speed;
public String time;
// deleted
public String device_name, geofence_name;
public boolean fitForFilter(String filterString) {
if(message.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(address.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(time.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(device_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(geofence_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
return false;
}
i am using REST API in backend and retrofit.
everything is ok untill i try to eun the app.
it says ERROR MESSAGE:
Process: com.gabontech.gprstest, PID: 14460
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabontech.gprstest/com.gabontech.gprstest.activities.MapActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3433)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3572)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2097)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7663)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.gabontech.gprstest.activities.MapActivity.onCreate(MapActivity.java:139)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
i think about the adapter where in EventsAdapter.class line ref:::::
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
ihave spent two days there. please if you can help it will give me a hand for my exam. Thank so much guys
To summarize, I'm building a social media app that displays:
A Newsfeed that shows posts from all user profiles in a given account
A Timeline that shows posts from a specific user profile in the account
I've built a custom BaseAdapter to populate a custom cell within each ListView. The Newsfeed ListView (that populates posts from all users on the account) is populating correctly.
The Timeline ListView (that populates posts from one profile on the account) is not showing. I've set breakpoints to ensure that my ArrayList is not null or empty when populating the Timeline ListView. In addition, breakpoints verify that my custom adapter is, in fact, pulling data from the ArrayList and inflating cells. However, the ListView is simply not visible.
Here is the layout file for my Newsfeed fragment (that is working correctly):
<android.support.constraint.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"
android:background="#color/colorSkyPrimary">
<android.support.constraint.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:elevation="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/input_post"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:backgroundTint="#color/colorSkyPrimary"
android:ems="10"
android:gravity="start|top"
android:hint="#string/what_s_going_on"
android:importantForAutofill="no"
android:inputType="textMultiLine"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:targetApi="o" />
<ImageButton
android:id="#+id/button_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:backgroundTint="#android:color/white"
android:contentDescription="#string/camera_button"
app:layout_constraintBottom_toBottomOf="#+id/input_post"
app:layout_constraintEnd_toEndOf="#+id/input_post"
app:srcCompat="#drawable/camera_icon" />
<Button
android:id="#+id/button_cancel"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginTop="8dp"
android:text="#android:string/cancel"
android:textColor="#color/colorGrassPrimary"
android:visibility="gone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/post_image" />
<Button
android:id="#+id/button_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="48dp"
android:backgroundTint="#color/colorGrassPrimary"
android:text="#string/update"
android:textColor="#color/colorButtonText"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/post_image" />
<ImageView
android:id="#+id/post_image"
android:layout_width="0dp"
android:layout_height="300dp"
android:contentDescription="#string/post_image"
android:scaleType="fitCenter"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/input_post"
tools:srcCompat="#tools:sample/avatars" />
</android.support.constraint.ConstraintLayout>
<ListView
android:id="#+id/list_newsfeed"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/picker_image"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout"
app:layout_constraintVertical_bias="0.0" />
<android.support.constraint.ConstraintLayout
android:id="#+id/picker_image"
android:layout_width="0dp"
android:layout_height="75dp"
android:background="#android:color/white"
android:elevation="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<android.support.constraint.Guideline
android:id="#+id/guideline14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<ImageButton
android:id="#+id/button_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:layout_marginBottom="8dp"
android:background="#android:color/transparent"
android:contentDescription="#string/camera_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline14"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/camera_icon_large" />
<ImageButton
android:id="#+id/button_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#android:color/transparent"
android:contentDescription="#string/gallery_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline14"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.375"
app:srcCompat="#drawable/gallery_icon" />
</android.support.constraint.ConstraintLayout>
Here is the layout file for my Profile fragment (in which the ListView is not showing at runtime)
<android.support.constraint.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"
android:background="#color/colorSkyPrimary">
<android.support.constraint.ConstraintLayout
android:id="#+id/constraintLayout4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:elevation="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_photo"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:src="#drawable/male_icon_large"
app:civ_border_color="#android:color/transparent"
app:civ_border_width="2dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/display_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/brelynn_mack"
android:textAlignment="viewStart"
android:textColor="#color/colorTextDark"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/button_delete_profile"
app:layout_constraintStart_toEndOf="#+id/profile_photo"
app:layout_constraintTop_toTopOf="#+id/profile_photo" />
<TextView
android:id="#+id/display_timestamp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="#string/may_14_2019_9_59_pm"
android:textAlignment="viewStart"
android:textColor="#color/colorTextLight"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/profile_photo"
app:layout_constraintTop_toBottomOf="#+id/display_name" />
<TextView
android:id="#+id/display_last_location"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/_8741_grouse_run_lane_28314"
android:textAlignment="viewStart"
android:textColor="#color/colorTextPrimary"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/profile_photo"
app:layout_constraintTop_toBottomOf="#+id/display_timestamp" />
<ImageButton
android:id="#+id/button_delete_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="#android:color/white"
android:contentDescription="#string/trash_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/trash_icon" />
<ImageButton
android:id="#+id/button_photo"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginStart="8dp"
android:layout_marginBottom="16dp"
android:background="#android:color/white"
android:contentDescription="#string/camera_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#+id/profile_photo"
app:layout_constraintTop_toBottomOf="#+id/profile_photo"
app:srcCompat="#drawable/camera_icon" />
<ImageButton
android:id="#+id/button_family"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:background="#android:color/white"
android:contentDescription="#string/family_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/family_icon_small" />
<ImageButton
android:id="#+id/button_gallery"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginEnd="8dp"
android:background="#android:color/transparent"
android:contentDescription="#string/gallery_button"
android:scaleType="fitCenter"
app:layout_constraintEnd_toEndOf="#+id/profile_photo"
app:layout_constraintTop_toBottomOf="#+id/profile_photo"
app:srcCompat="#drawable/gallery_icon" />
</android.support.constraint.ConstraintLayout>
<ListView
android:id="#+id/list_posts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout4" />
Here is my custom adapter:
public class NewsfeedAdapter extends BaseAdapter {
// Class properties
private static final String TAG = "NewsfeedAdapter";
public static final String EXTRA_POSTS = "extra_posts";
public static final String EXTRA_POSITION = "extra_position";
private final Context context;
ArrayList<Post> posts;
Account account;
// Constructor
public NewsfeedAdapter(Context context, ArrayList<Post> posts, Account account) {
this.context = context;
this.posts = posts;
this.account = account;
}
// System generated methods
#Override
public int getCount() {
return posts.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return posts.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Post post = posts.get(position);
if(convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.cell_newsfeed, null);
}
TextView profileNameDisplay = convertView.findViewById(R.id.display_profile_name);
String name = post.getPosterName() + " " + account.getFamilyName();
profileNameDisplay.setText(name);
TextView timestampDisplay = convertView.findViewById(R.id.display_timestamp);
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy # hh:mm a", Locale.getDefault());
String timestamp = dateFormat.format(post.getTimeStamp());
timestampDisplay.setText(timestamp);
TextView postMessageDisplay = convertView.findViewById(R.id.display_post_message);
postMessageDisplay.setText(post.getPostMessage());
if (post.getHasImage()) {
AccountUtils.loadProfilePhoto(context, convertView, post.getPosterId());
}
else {
ImageView postImage = convertView.findViewById(R.id.display_post_image);
postImage.setVisibility(View.GONE);
}
PostUtils.loadPostImage(convertView, post.getPostId());
ImageButton deleteButton = convertView.findViewById(R.id.button_delete_post);
ImageButton editButton = convertView.findViewById(R.id.button_edit_post);
toggleButtons(post, editButton, deleteButton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setTitle(context.getString(R.string.delete_post));
alertBuilder.setMessage(context.getString(R.string.delete_post_message));
alertBuilder.setPositiveButton(context.getString(R.string.delete), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
posts.remove(position);
PostUtils.deletePost(context, post.getPostId(), post.getPosterId());
notifyDataSetChanged();
PostUtils.listenForNews(context);
}
});
alertBuilder.setNegativeButton(context.getString(R.string.cancel), null);
AlertDialog alert = alertBuilder.create();
alert.show();
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent editIntent = new Intent(context, EditPostActivity.class);
editIntent.putExtra(EXTRA_POSTS, posts);
editIntent.putExtra(EXTRA_POSITION, position);
context.startActivity(editIntent);
}
});
return convertView;
}
// Custom methods
private void toggleButtons(Post post, ImageButton editButton, ImageButton deleteButton) {
long twoMinutes = System.currentTimeMillis() - (2 * 60 * 1000);
long fiveMinutes = System.currentTimeMillis() - (5 * 60 * 1000);
if (post.getTimeStamp().getTime() < fiveMinutes) {
editButton.setVisibility(View.GONE);
}
else {
editButton.setVisibility(View.VISIBLE);
}
if (post.getTimeStamp().getTime() < twoMinutes) {
deleteButton.setVisibility(View.GONE);
}
else {
deleteButton.setVisibility(View.VISIBLE);
}
}
Here are the lifecycle methods from the Newsfeed fragment that load my data and set the adapter:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newsfeed, container, false);
PostUtils.listenForNews(getActivity());
mPosts = PostUtils.loadNewsfeed(getActivity());
mNewsfeed = view.findViewById(R.id.list_newsfeed);
mImagePicker = view.findViewById(R.id.picker_image);
mPhotoView = view.findViewById(R.id.post_image);
AccountUtils.listenForUpdates(getActivity());
setClickListener(view);
setFocusListener(view);
return view;
}
#Override
public void onResume() {
super.onResume();
mPosts = PostUtils.loadNewsfeed(getActivity());
Account account = AccountUtils.loadAccount(getActivity());
mNewsfeedAdapter = new NewsfeedAdapter(getActivity(), mPosts, account);
mNewsfeed.setAdapter(mNewsfeedAdapter);
}
Here are the lifecycle methods from my Profile fragment where the same functionality should work for a slightly different set of data:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
try {
if(getActivity().getIntent() != null && getActivity().getIntent().getAction().equals(FamilyProfileFragment.ACTION_EDIT_PROFILE)) {
mEditingSelf = false;
mIsParent = true;
mProfile = (Profile) getActivity().getIntent().getSerializableExtra(FamilyProfileFragment.EXTRA_PROFILE);
String selectedName = mProfile.getFirstName();
String loadedName = AccountUtils.loadProfile(getActivity()).getFirstName();
if(selectedName.equals(loadedName)) {
mEditingSelf = true;
}
}
else {
mEditingSelf = true;
mProfile = AccountUtils.loadProfile(getActivity());
if(mProfile instanceof Parent) {
mIsParent = true;
}
else {
mIsParent = false;
}
}
}
catch (Exception e) {
e.printStackTrace();
mEditingSelf = true;
mProfile = AccountUtils.loadProfile(getActivity());
if(mProfile instanceof Parent) {
mIsParent = true;
}
else {
mIsParent = false;
}
}
mAccount = AccountUtils.loadAccount(getActivity());
AccountUtils.loadProfilePhoto(getActivity(), view, mProfile.getProfileId());
mPhotoView = view.findViewById(R.id.profile_photo);
PostUtils.listenForTimeline(getActivity(), mProfile);
mPosts = PostUtils.loadTimeline(getActivity());
mTimeline = view.findViewById(R.id.list_posts);
setClickListener(view);
setTextDisplay(view);
populateProfile(view);
return view;
}
#Override
public void onResume() {
super.onResume();
mPosts = PostUtils.loadTimeline(getActivity());
mNewsfeedAdapter = new NewsfeedAdapter(getActivity(), mPosts, mAccount);
mTimeline.setAdapter(mNewsfeedAdapter);
}
My constraints were set up incorrectly in the Profile fragment. Updated the XML to the following:
<ListView
android:id="#+id/list_newsfeed"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout4" />
This question already has answers here:
NPE while inflating layout (Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference)
(2 answers)
Closed 4 years ago.
Fragment makes it out of onCreateView whenever I switch out the layout, leading me to believe the problem is within the xml file itself
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation = "vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:textColor="#FFFFFF"
android:background="#color/lining"
android:text="Añadir actividad"
android:textStyle="bold"/>
<view
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_marginBottom="10dp"
android:background="#color/lining" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Nombre de actividad"
android:textAlignment="center"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:id="#+id/activity_name"/>
</LinearLayout>
<view
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:background="#color/lining" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Prioridad"
android:textAlignment="center"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20dp"
android:id="#+id/priority"/>
</LinearLayout>
<view
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:background="#color/lining" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Añadir fecha"
android:id="#+id/date_select"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fecha"
android:textSize="20dp"
android:text="--/--/----"
android:textAlignment="center"/>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
the AddFragment.java:
public class AddFragment extends Fragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener{
EditText activityName;
Spinner priority;
Button dateSelected;
TextView date;
View v;
Context context;
CallBackToMain backToMain;
Entrada modify;
FloatingActionButton actionButton;
String dateStrung = "";
public static AddFragment newInstance(Entrada e) {
Bundle args = new Bundle();
args.putSerializable("entrada", e);
AddFragment fragment = new AddFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.addfragment, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
backToMain = (CallBackToMain) context;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
instance();
config();
actions();
}
public void instance(){
modify = (Entrada) getArguments().getSerializable("entrada");
date = v.findViewById(R.id.fecha);
dateSelected = v.findViewById(R.id.date_select);
activityName = v.findViewById(R.id.activity_name);
priority = v.findViewById(R.id.priority);
actionButton = v.findViewById(R.id.save);
}
private void config(){
if (modify != null){
activityName.setText(modify.getNombreActividad());
priority.setSelection(modify.getPrioridad());
date.setText(modify.returnDateInFormat());
String [] fullDateSplit = date.getText().toString().split("/");
dateStrung = fullDateSplit[2] + fullDateSplit[1] + fullDateSplit[0];
}
String[] values = {"Alta", "Media", "Baja"};
priority.setAdapter(new ArrayAdapter(context, android.R.layout.simple_list_item_1, values));
}
private void actions(){
actionButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.date_select){
new DatePickerDialog(context, AddFragment.this,
Calendar.getInstance().get(Calendar.getInstance().YEAR),
Calendar.getInstance().get(Calendar.getInstance().MONTH),
Calendar.getInstance().get(Calendar.getInstance().DAY_OF_MONTH)).show();
}
else if (v.getId() == R.id.save){
backToMain.backToMain(new Entrada(0, activityName.getText().toString(), (byte) priority.getSelectedItemPosition(), dateStrung));
}
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//Si no, 0 es enero, 1 es febrero, etc.
month++;
//
if(year < Calendar.YEAR || (year == Calendar.YEAR && month < Calendar.MONTH) || (year == Calendar.YEAR && month == Calendar.MONTH && dayOfMonth < Calendar.DAY_OF_MONTH)){
new AlertDialog.Builder(context).setTitle("Fecha invalida").setMessage("Fecha anterior al día presente").show();
}
else{
dateStrung = year + "" + month + "" + dayOfMonth;
date.setText(dayOfMonth + "/" + month + "/" + year);
}
}
public interface CallBackToMain{
void backToMain(Entrada e);
}
}
It simply comes to a dead halt in:
v = inflater.inflate(R.layout.addfragment, container, false);
with the error java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
I've revised the java and the xml code countless times, but I can't seem to find the root cause of this, and to top it off it's a string.equals that seems to be the biggest culprit here, so I simply don't understand what could be happening...
Can anyone lend me a hand? I'm a bit of a rookie, it that hasn't been made clear yet ^^;
This is a simple typo error. Because you're using the following xml:
<view> .... </>
which is incorrect because it's not starting with uppercase. The correct one:
<View> .... </>
I'm developing a Calorie app where the user can delete an item from the listview.
PROBLEM: When the user clicks on the item it goes to the calorie details activity,when they click delete it goes back to the home fragment. As soon as I click on add another entry it crashes. Also when it goes back to fragment home it doesnt look the same the calorie details activity is over lapping the fragment home not completely replacing it.
calorieDetails.java
public class CalorieDetails extends AppCompatActivity {
private TextView foodName, calories, dateTaken;
private Button shareButton;
private int foodId;
private Button deleteButton;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_details);
foodName = (TextView) findViewById(R.id.detsFoodName);
calories = (TextView) findViewById(R.id.detscaloriesValue);
dateTaken = (TextView) findViewById(R.id.detsDateText);
deleteButton = (Button) findViewById(R.id.deleteButton);
Food food = (Food) getIntent().getSerializableExtra("userObj");
foodName.setText(food.getFoodName());
calories.setText(String.valueOf(food.getCalories()));
dateTaken.setText(food.getRecordDate());
foodId = food.getFoodId();
foodName.setTextColor(Color.WHITE);
dateTaken.setTextColor(Color.WHITE);
calories.setTextSize(34.9 f);
calories.setTextColor(Color.WHITE);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: put delete functionality here
android.support.v7.app.AlertDialog.Builder alert = new
android.support.v7.app.AlertDialog.Builder(CalorieDetails.this);
alert.setTitle("Delete?");
alert.setMessage("Are you sure you want to delete this item?");
alert.setNegativeButton("No", null);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHandler dba = new
DatabaseHandler(getApplicationContext());
dba.deleteFood(foodId);
Toast.makeText(CalorieDetails.this, "Food Item
Deleted!", Toast.LENGTH_SHORT).show();
FragmentHome homeFragment = new FragmentHome();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentHolder,
homeFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
}
});
alert.show();
}
});
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
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();
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();
}
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();
}
//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();
break;
}
}
activity_calorie_details.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:id="#+id/FragmentHolder"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
tools:context=".CalorieDetails"
android:background="#drawable/imgbackground2"
style="#style/AppTheme">
<ImageView
android:id="#+id/logo"
android:src="#drawable/weight"
android:layout_centerHorizontal="true"
android:layout_width="180dp"
android:layout_height="180dp" />
<LinearLayout
android:id="#+id/layout"
android:elevation="4dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/detsFoodName"
android:elevation="4dp"
android:text="dkdad"
android:textSize="19sp"
android:textStyle="bold"
android:layout_marginTop="18dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsCaloriesTitle"
android:text="Calories:"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detscaloriesValue"
android:text="200"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsDateText"
android:text="Consumed on..."
android:textStyle="italic"
android:textSize="14sp"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/deleteButton"
android:text="DELETE"
android:textColor="#ffff"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"
android:layout_width="200dp"
android:background="#color/colorBackground2"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Home_fragment.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="#drawable/imgbackground2"
style="#style/AppTheme"
tools:context="layout.HomeFragment"
android:id="#+id/HomeFragment">
<RelativeLayout
android:layout_width="match_parent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_height="271dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome,"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="85dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="24dp"
android:textSize="24sp"
android:textColor="#ffffff"
android:text="#string/activity_text_calorie_title"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_calorie_amount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
tools:text="1600"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_below="#+id/tv_main_title"
android:layout_alignParentStart="true"
android:gravity="center"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/AddItems"
android:background="?android:attr/selectableItemBackground"
android:src="#drawable/add"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:layout_below="#+id/tv_calorie_amount"
android:layout_alignParentEnd="true" />
<TextView
tools:text="1600"
android:id="#+id/calorieRemain"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_below="#+id/tv_main_title"
android:layout_toEndOf="#+id/textView" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ResetEntry"
android:background="?android:attr/selectableItemBackground"
android:src="#drawable/removecircle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:paddingRight="0dp"
android:layout_alignBottom="#+id/AddItems"
android:layout_toStartOf="#+id/AddItems" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="274dp"
android:layout_gravity="center_horizontal|bottom">
<ListView
android:id="#+id/ListId"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:dividerHeight="2dp"
android:divider="#212121"
android:scrollingCache="false"
android:smoothScrollbar="false"
android:layout_below="#+id/tv_calorie_amount"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"></ListView>
</LinearLayout>
</FrameLayout>
Here is a screenshot of what happens after clicking delete:
http://www.tiikoni.com/tis/view/?id=c0939b3
Here is what the Home Fragment Looks like before deleting item:
http://www.tiikoni.com/tis/view/?id=70e433d
logcat when I click Delete on the Calorie Details fragment
05-04 02:25:25.561 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: mSContextService =
android.hardware.scontext.ISContextService$Stub$Proxy#14b764b
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#42e6828
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#42e6828
05-04 02:25:25.581 5830-5830/com.example.treycoco.calorietracker
E/ViewRootImpl: sendUserActionEvent() mView == null
When I click on Add Entry After Clicking on Delete
Logcat:
05-04 02:28:04.761 5830-
5830/com.example.treycoco.calorietracker E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 5830
java.lang.ClassCastException
com.example.treycoco.calorietracker.CalorieDetails cannot be cast
to com.example.treycoco.calorietracker.appMain
at com.example.treycoco.calorietracker.
FragmentHome$1.onClick(FragmentHome.java:118)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I have an adapter with buttons and text views. It represents friend requests.
TextView text would be : Do you want to accept X as your friend?
There are 2 buttons : one for accepting, one for declining. Pressing Decline, it would just remove the row from the ListView, while pressing accept will change the text into: X and Y are now friends.
My question is how can I get the position of the row and change it on button press and also save the View for next time I access it?
Adapter : At the moment I don't have proper data structure for the adapter, so for testing purposes, just using a String:
public class FriendRequestAdapter extends BaseAdapter {
String mName;
Context mContext;
public FriendRequestAdapter(String name, Context context) {
this.mName = name;
this.mContext = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.friend_request_layout, null);
}
TextView sender_name = (TextView) convertView.findViewById(R.id.wannabe_name);
if (mName.length() > 11) {
mName = mName.substring(0, 12);
}
sender_name.setText(mName);
ImageButton friend_request_accepted = (ImageButton) convertView.findViewById(R.id.accept_friend_request);
friend_request_accepted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
new APIService().confirmInvite();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
});
return convertView;
}
Inflated Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/changing_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/check_in_map_menu"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/friend_image_container"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="7dp"
android:background="#drawable/polaroid_frame_friend_list">
<ImageView
android:id="#+id/facebook_friend_pic"
android:layout_width="55dp"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:background="#drawable/category_explore"/>
<TextView
android:id="#+id/name_facebook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/facebook_friend_pic"
android:layout_centerHorizontal="true"
android:text="dummy"
android:textColor="#color/enloop_dark_gray"
android:textSize="9sp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:layout_toRightOf="#+id/friend_image_container">
<TextView
android:id="#+id/wannabe_name"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:text="dada"
android:textColor="#color/enloop_dark_gray"
android:textSize="15dp"/>
<TextView
android:id="#+id/facebook_friend_name"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/wannabe_name"
android:text=" has sent you a request"
android:textColor="#color/enloop_dark_gray"
android:textSize="15dp"/>
<ImageButton
android:id="#+id/later_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:background="#drawable/btn_nothanks"
android:clickable="false"
android:focusable="false"/>
<ImageButton
android:id="#+id/accept_friend_request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:layout_toRightOf="#+id/later_button"
android:background="#drawable/btn_accept_text"
android:clickable="false"
android:focusable="false"/>
<ImageButton
android:id="#+id/invite_facebook_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/btn_delete_notification"
android:clickable="false"
android:focusable="false"/>
</RelativeLayout>
</RelativeLayout>