Home > Software engineering >  How to set binding in a Fragment?
How to set binding in a Fragment?

Time:04-15

I'm trying to build a "Note taking" area in my app. I'm having problems with the view binding specifically. i followed this code example "https://codingwithsaud.medium.com/how-to-make-note-app-in-android-studio-part-1-443ccf16921e" to a T, but its mainly built in an activity not a fragment. I'm currently building it in an fragment and everything else is good besides my "Equipment_Tracker.kt" i cant figure out whats going wrong. The list problems take place in the "Equipment_Tracker.kt" Thanks in advance for helping.

List off errors popping up.

Unresolved reference: setContentView
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time

Type mismatch: inferred type is Equipment_Tracker but Context? was expected

Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time

None of the following functions can be called with the arguments supplied:
public constructor Intent(p0: Context!, p1: Class<*>!) defined in android.content.Intent
public constructor Intent(p0: String!, p1: Uri!) defined in android.content.Intent

Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
Smart cast to 'FragmentEquipmentTrackerBinding' is impossible, because 'binding' is a mutable property that could have been changed by this time
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast

Equipment_Tracker.kt

package com.example.armymaintenance

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.armymaintenance.Model.note_model
import com.example.armymaintenance.database.MySqliteHelper
import com.example.armymaintenance.databinding.FragmentEquipmentTrackerBinding

class Equipment_Tracker : Fragment() {
    

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_equipment__tracker, container, false)

    }

    var binding: FragmentEquipmentTrackerBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentEquipmentTrackerBinding.inflate(layoutInflater)
        setContentView(binding.getRoot())
        val helper = MySqliteHelper(this)
        binding.btnDisplay.setOnClickListener(View.OnClickListener {
            val intent = Intent(this@Equipment_Tracker, Equipment_Tracker::class.java)
            startActivity(intent)
        })
        binding.btnSave.setOnClickListener(View.OnClickListener {
            val model = note_model()
            model.bumpernumber = binding.bumpernumber.text.toString()
            model.description = binding.description.text.toString()
            model.nsn = binding.nsn.text.toString()
            model.serialnumber = binding.serialnumber.text.toString()
            model.date = binding.date.text.toString()
            if (model.bumpernumber.isEmpty()) {
                binding.bumpernumber.error = "Enter bumper number"
                return@OnClickListener
            }
            if (model.description.isEmpty()) {
                binding.description.error = "Enter description"
                return@OnClickListener
            }
            if (model.nsn.isEmpty()) {
                binding.nsn.error = "Enter nsn"
                return@OnClickListener
            }
            if (model.serialnumber.isEmpty()) {
                binding.serialnumber.error = "Enter serial number"
                return@OnClickListener
            }
            if (model.date.isEmpty()) {
                binding.date.error = "Enter date"
                return@OnClickListener
            }
            val r = helper.saveNote(model)
            if (r) {
                Toast.makeText(this@Equipment_Tracker, "note is saved", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@Equipment_Tracker, "some thing want wrong", Toast.LENGTH_SHORT)
                    .show()
            }
        })
    }

}

fragment_equipment_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Equipment_Tracker">

    <LinearLayout
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@ id/bumpernumber"
            android:hint="Bumper Number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@ id/description"
            android:hint="Enter description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@ id/nsn"
            android:hint="Enter nsn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@ id/serialnumber"
            android:hint="Enter serial number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@ id/date"
            android:hint="Enter date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@ id/btnSave"
            android:text="Save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@ id/btnDisplay"
            android:text="Display"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

note_model.java

package com.example.armymaintenance.Model;

public class note_model {

    private int id;
    private String bumpernumber;
    private String description;
    private String nsn;
    private String serialnumber;
    private String date;

    public note_model() {
    }

    public note_model(int id, String bumpernumber, String description, String nsn, String serialnumber, String date) {
        this.id = id;
        this.bumpernumber = bumpernumber;
        this.description = description;
        this.nsn = nsn;
        this.serialnumber = serialnumber;
        this.date = date;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBumpernumber() {
        return bumpernumber;
    }

    public void setBumpernumber(String bumpernumber) {
        this.bumpernumber = bumpernumber;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    public String getNsn() {
        return nsn;
    }

    public void setNsn(String nsn) {
        this.nsn = nsn;
    }

    public String getSerialnumber() {
        return serialnumber;
    }

    public void setSerialnumber(String serialnumber) {
        this.serialnumber = serialnumber;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

MySqliteHelper.java

package com.example.armymaintenance.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.armymaintenance.Model.note_model;

import java.util.ArrayList;
import java.util.List;

public class MySqliteHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="note.db";
    private static final int VERSION=1;
    public MySqliteHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String table1="create table " TableSchema.note.TABLE_NAME "(" TableSchema.note.ID " INTEGER PRIMARY KEY AUTOINCREMENT, " TableSchema.note.BUMPERNUMBER " TEXT, " TableSchema.note.DESCRIPTION " TEXT," TableSchema.note.NSN " TEXT," TableSchema.note.SERIALNUMBER " TEXT, " TableSchema.note.DATE " TEXT );";
        sqLiteDatabase.execSQL(table1);
    }

    public boolean saveNote(note_model model){
        SQLiteDatabase database=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
        cv.put(TableSchema.note.DESCRIPTION,model.getDescription());
        cv.put(TableSchema.note.NSN,model.getNsn());
        cv.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
        cv.put(TableSchema.note.DATE,model.getDate());
        long id= database.insert(TableSchema.note.TABLE_NAME,null,cv);
        if (id==-1){
            return false;
        }
        return true;
    }
    public List<note_model> getAllNotes(){
        SQLiteDatabase database= this.getReadableDatabase();
        String[] cols={TableSchema.note.ID,TableSchema.note.BUMPERNUMBER,TableSchema.note.DESCRIPTION,TableSchema.note.NSN,TableSchema.note.SERIALNUMBER,TableSchema.note.DATE};
        Cursor cursor=database.query(TableSchema.note.TABLE_NAME,cols,null,null,null,null,TableSchema.note.ID " DESC");
        ArrayList<note_model> list=new ArrayList<>();
        while (cursor.moveToNext()){
            note_model model=new note_model();
            model.setId(cursor.getInt(cursor.getColumnIndex(TableSchema.note.ID)));
            model.setBumpernumber(cursor.getString(cursor.getColumnIndex(TableSchema.note.BUMPERNUMBER)));
            model.setDescription(cursor.getString(cursor.getColumnIndex(TableSchema.note.DESCRIPTION)));
            model.setNsn(cursor.getString(cursor.getColumnIndex(TableSchema.note.NSN)));
            model.setSerialnumber(cursor.getString(cursor.getColumnIndex(TableSchema.note.SERIALNUMBER)));
            model.setDate(cursor.getString(cursor.getColumnIndex(TableSchema.note.DATE)));
            list.add(model);
        }
        cursor.close();
        database.close();
        return list;
    }
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        if (i<i1){
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " TableSchema.note.TABLE_NAME);
        }

    }
}

TableSchema.java

package com.example.armymaintenance.database;

public class TableSchema {

    public static class note{

        public static final String TABLE_NAME="tbl_note";
        public static final String ID="id";
        public static final String BUMPERNUMBER="bumpernumber";
        public static final String DESCRIPTION="description";
        public static final String NSN="nsn";
        public static final String SERIALNUMBER="serialnumber";
        public static final String DATE="date";
    }

}

CodePudding user response:

Binding is wrong Please check this documentation for the view Binding https://developer.android.com/topic/libraries/view-binding#kts

In Activity you can initialize the lateinit var binding: ActivityMainBinding and can inflate the view like this

 binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view) 

But for the fragments the way is different

private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!

and in onCreateView method you have to do it like this

_binding = FragmentMainBinding.inflate(inflater, container, false)
    val view = binding.root
    return view

Please make sure that you do it in onCreateView not in onViewCreated

and in onDestroyView you have to set its value to null

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

That is the Proper way of doing binding you can also visit the documentation for more information

  • Related