ListView во фрагменте - PullRequest
       3

ListView во фрагменте

0 голосов
/ 12 января 2019

Я работаю над школьным проектом. Я разрабатываю приложение для тренировок, в котором у меня есть ящик, и когда я выбираю Упражнения, в которых я хочу просмотреть список частей тела, я получаю «java.lang.NullPointerException: попытка вызвать виртуальный метод» void android.widget.ListView.setAdapter (android .widget.ListAdapter) 'для ссылки на пустой объект " и я не могу понять, в чем проблема, как 4 часа. спасибо за помощь

Я попытался повторно сделать адаптер, массив и так далее. Я уже попробовал список во втором приложении, где оно работает.

Это показывает, что проблема в mListView.setAdapter (адаптер); в упражнении фрагмент /

MainActivity.class

public class MainActivity extends AppCompatActivity implements 
NavigationView.OnNavigationItemSelectedListener {

//variables
boolean doubleBackToExitPressedOnce = false;

// objects
private TextView mTextUsername;
private FrameLayout mFragmentContainer;
private EditText mEditTextSend;
private Button mButtonSend;

//plugin objects
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;

//drawer
private DrawerLayout mDrawer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    assignVariables(); // funkcia na priradenie findViewById
    // navigation drawer
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // refering to navigation view
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(MainActivity.this);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(MainActivity.this, mDrawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    mDrawer.addDrawerListener(toggle);
    toggle.syncState();


    //open profile fragment when app starts
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new ProfileFragment()).commit();
        navigationView.setCheckedItem(R.id.nav_profile);
    } // v drawer bude "zakliknute" profile

    mFirebaseAuth = FirebaseAuth.getInstance();


}


private void assignVariables() {     // funkcia na priradenie findViewById
    mDrawer = findViewById(R.id.drawer_layout);
    mTextUsername = findViewById(R.id.text_view_drawer_text_username);
    mFragmentContainer = findViewById(R.id.fragment_container);
    //mEditTextSend = findViewById(R.id.button_fragment_food_send);
    mButtonSend = findViewById(R.id.button_fragment_food_send);


}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    // which fragment to open
    switch (menuItem.getItemId()) {
        case R.id.nav_calendar:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new CalendarFragment()).commit();
            break;

        case R.id.nav_profile:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ProfileFragment()).commit();
            break;
        case R.id.nav_exercises:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ExercisesFragment()).commit();
            break;
        case R.id.nav_food:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new FoodFragment()).commit();
            break;

        case R.id.drawer_logout:
            Logout();
            break;

        case R.id.nav_settings:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new SettingsFragment()).commit();
            break;


    }

    // close drawer
    mDrawer.closeDrawer(GravityCompat.START);
    return true;
}

private void Logout() {
    mFirebaseAuth.signOut();
    finish();
    startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
}

public void exit() {
    moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(1);
}

@Override
public void onBackPressed() {
    if (mDrawer.isDrawerOpen(GravityCompat.START)) { // if drawer is oppened == close
        mDrawer.closeDrawer(GravityCompat.START);
    } else { // if drawer is closed == double click to exit
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            exit();     // DOLADIT
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(MainActivity.this, "Press one more time to exit app", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }
}
}

ExercisesFragment.class

public class ExercisesFragment extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    View mView = inflater.inflate(R.layout.fragment_exercises, container, 
false);
    ListView mListView = mView.findViewById(R.id.listView);
    // create body part objects
    BodyPart chest = new BodyPart("Chest", R.drawable.chest);
    BodyPart back = new BodyPart("Back", R.drawable.back);
    BodyPart triceps = new BodyPart("Triceps", R.drawable.triceps);
    BodyPart biceps = new BodyPart("Biceps", R.drawable.biceps);
    BodyPart shoulders = new BodyPart("Shoulders", R.drawable.shoulder);
    BodyPart legs = new BodyPart("Legs", R.drawable.legs);
    BodyPart abs = new BodyPart("Abs", R.drawable.abs);

    ArrayList<BodyPart> mBodyPartList = new ArrayList<>();
    mBodyPartList.add(chest);
    mBodyPartList.add(back);
    mBodyPartList.add(triceps);
    mBodyPartList.add(biceps);
    mBodyPartList.add(shoulders);
    mBodyPartList.add(legs);
    mBodyPartList.add(abs);

    BodyPartAdapter adapter = new BodyPartAdapter(getActivity(), 
R.layout.body_parts_list_layout, mBodyPartList);
    mListView.setAdapter(adapter);

    mListView.setOnItemClickListener(new 
AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,int 
position, long id) {
            // TODO Auto-generated method stub
            if(position == 0) {
                //code specific to first list item

Toast.makeText((getActivity()).getApplicationContext(),"Place Your First 
Option Code",Toast.LENGTH_SHORT).show();
            }

            else if(position == 1) {
                //code specific to 2nd list item

Toast.makeText((getActivity()).getApplicationContext(),"Place Your Second 
Option Code",Toast.LENGTH_SHORT).show();
            }

            else if(position == 2) {


Toast.makeText((getActivity()).getApplicationContext(),"Place Your Third 
Option Code",Toast.LENGTH_SHORT).show();
            }
            else if(position == 3) {


Toast.makeText((getActivity()).getApplicationContext(),"Place Your Forth 
Option Code",Toast.LENGTH_SHORT).show();
            }
            else if(position == 4) {


Toast.makeText((getActivity()).getApplicationContext(),"Place Your Fifth 
Option Code",Toast.LENGTH_SHORT).show();
            }

        }
    });
return mView;
}
}

BodyPartAdapter.class

public class BodyPartAdapter extends ArrayAdapter<BodyPart> {

private Context mContext;
int mResource;

/**
 *
 * @param context
 * @param resource
 * @param objects
 */
public BodyPartAdapter(Context context, int resource, ArrayList<BodyPart> 
objects) {
    super(context, resource, objects);

    mContext = context;
    mResource = resource;

}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // get the boy part info
    String part = getItem(position).getName();
    Integer icon = getItem(position).getIcon();

    // create the body part object with the info
    BodyPart bodyPart = new BodyPart(part, icon);

    LayoutInflater inflater = LayoutInflater.from(mContext);
    convertView = inflater.inflate(mResource, parent, false);

    // declare text view objects and set bodypart and icon to text&image 
     views
    TextView tvBody = convertView.findViewById(R.id.title);
    ImageView imIcon = convertView.findViewById(R.id.icon);

    tvBody.setText(part);
    imIcon.setImageResource(icon);

    return convertView;
}
}

FragmentExercises.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"

tools:context="com.admk.workoutdiary.MainActivity">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_marginStart="0dp"
    android:layout_marginBottom="50dp" />
</RelativeLayout>

body_parts_list_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/listView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100">

<ImageView
    android:id="@+id/icon"
    android:layout_width="match_parent"
    android:layout_height="75dp"
    android:padding="15dp"
    android:layout_weight="80"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="66.6"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:padding="2dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#4d4d4d"
        android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...