Activity不能为null错误,Kotlin android

时间:2019-02-09 14:01:16

标签: android android-studio android-activity kotlin fragment

我在Tablayout的“ Home”,“ Market”,“ Office”和“ Admin”中有4个片段,而在Sqlite中的“ Home”,“ Office”和“ Market”中有3个表。在Admin片段中,admin使用表中的数据名称并存储在其各自的表中,并在每个各自的片段的recyclerView中显示,但它显示活动不能为空

  

Admin_Fragment

package com.example.muhammadrizwan.deafanddumbcommunicationaid.Fragments


import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import com.example.muhammadrizwan.deafanddumbcommunicationaid.Model.Data
import com.example.muhammadrizwan.deafanddumbcommunicationaid.Model.DbHelper

import com.example.muhammadrizwan.deafanddumbcommunicationaid.R
import java.io.ByteArrayOutputStream

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 *
 */
class Admin_Fragment : Fragment() {

    private lateinit var image: ImageView
    private lateinit var text1: EditText
    private lateinit var text2: EditText
    private lateinit var addBtn: Button
    private lateinit var Txttitle: String
    private lateinit var Iname: String
    private var GalleryCode: Int = 200
    private var CameraCode: Int = 100
    lateinit var stream : ByteArrayOutputStream
    lateinit var ByteImage : ByteArray
    var database = DbHelper(activity)
    var sql = database.writableDatabase
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_admin_, container, false)

        var data = Data()
        data.text = Txttitle
        data.Image = ByteImage
        data.InterfaceName = Iname
        database.InsertData(data)
        image = view.findViewById<ImageView>(R.id.imageView)
        text1 = view.findViewById<EditText>(R.id.title)
        text2 = view.findViewById<EditText>(R.id.name)
        addBtn = view.findViewById<Button>(R.id.AddBtn)
        addBtn.setOnClickListener {
            validate()
        }
        return  view
    }

    private fun validate() {
        if(!text1.text.isEmpty())
        {
            Txttitle = text1.text.trim().toString()

            if(!text2.text.isEmpty())
            {
                 Iname = text2.text.trim().toString()
            }else{
              text2.setError("Enter Interface Name")
            }
        }
        else{
            text1.setError("Enter Title")
        }
        image.setOnClickListener {
                var builder = AlertDialog.Builder(activity)
                builder.setTitle("Make Choice")
                var option = arrayOf("Capture","Gallery")
                builder.setItems(option,object : DialogInterface.OnClickListener
                {
                    override fun onClick(p0: DialogInterface?, p1: Int) {
                        if(option[p1].equals("Capture"))
                        {
                            openCamera()
                        }
                        else
                        {
                            openGallery()
                        }
                    }

                })
            builder.show()
        }

    }



    private fun openGallery() {
        if(ContextCompat.checkSelfPermission(activity,android.Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
        {
            var intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent,GalleryCode)
        }else{
            ActivityCompat.requestPermissions(activity, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),GalleryCode)
        }
    }
    private fun openCamera() {
        if(ContextCompat.checkSelfPermission(activity,android.Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED)
        {
                var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                startActivityForResult(intent,CameraCode)
        }else{
            ActivityCompat.requestPermissions(activity, arrayOf(android.Manifest.permission.CAMERA),CameraCode)
        }

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when(requestCode)
        {
            CameraCode->
            {
                if(grantResults.size>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                {
                    openCamera()
                }
            }
            GalleryCode->
            {
                if(grantResults.size>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                {
                    openGallery()
                }
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode)
        {
            CameraCode->
            if(resultCode == Activity.RESULT_OK)
            {
                var bitmap = data?.extras?.get("data")
                image.setImageBitmap(bitmap as Bitmap)
                stream = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.PNG,100,stream)
                ByteImage = stream.toByteArray()
            }
            GalleryCode->
            if(resultCode == Activity.RESULT_OK)
            {
                var Uri = data!!.data
                var bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver,Uri)
                stream = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.PNG,100,stream)
                ByteImage = stream.toByteArray()
            }
        }
    }





}
  

DbHelper

package com.example.muhammadrizwan.deafanddumbcommunicationaid.Model

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast

class DbHelper(var ctx:Context) :  SQLiteOpenHelper(ctx,"Deaf and Dumb",null,1) {

    val TableHome = "Home"
    val TableOffice = "Office"
    val TableMarket = "Market"
//    val HomeText = "Home Text"
//    val HomeImage = "Blob"
//    val OfficeText = "Office Text"
//    val OfficeImage = "Blob"


    override fun onCreate(db: SQLiteDatabase?) {
        val TableHome = "CREATE TABLE $TableHome (Text STRING , Image BLOB)"
        val TableOffice = "CREATE TABLE $TableOffice (Text STRING , Image BLOB)"
        val TableMarket = "CREATE TABLE $TableMarket (Text STRING , Image BLOB)"
        db!!.execSQL(TableHome)
        db!!.execSQL(TableOffice)
        db!!.execSQL(TableMarket)
    }

    override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {

    }

    fun InsertData(data: Data) {
        var dbHelper = DbHelper(ctx)
        var database = dbHelper.writableDatabase
        var values = ContentValues()
        values.put("Text", data.text)
        values.put("Image", data.Image)
        values.put("Interface Name", data.InterfaceName)
        if (data.InterfaceName.equals("HOME")) {
            database.insert("$TableHome", null, values)
            Toast.makeText(ctx, "Inserted in $TableHome", Toast.LENGTH_SHORT).show()
        } else if (data.InterfaceName.equals("OFFICE")) {
            database.insert("$TableOffice", null, values)
            Toast.makeText(ctx, "Inserted in $TableHome", Toast.LENGTH_SHORT).show()
        } else if (data.InterfaceName.equals("MARKET")) {
            database.insert("$TableMarket", null, values)
        }
        dbHelper.close()
    }

    fun getHomeData(): List<Data> {
        var HomeList = ArrayList<Data>()
        var dbHelper = writableDatabase
        val sqlQuery = "SELECT * FROM $TableHome"
        var cursor = dbHelper.rawQuery(sqlQuery, null)
        if (cursor != null) {
            cursor.moveToFirst()
            do {
                var data = Data()
                data.text = cursor.getString(cursor.getColumnIndex("Text"))
                data.Image = cursor.getBlob(cursor.getColumnIndex("Image"))
            } while (cursor.moveToNext())
        }
        return HomeList
    }

    fun getofficeData(): List<Data> {
        var OfficeList = ArrayList<Data>()
        var dbHelper = writableDatabase
        val sqlQuery = "SELECT * FROM $TableOffice"
        var cursor = dbHelper.rawQuery(sqlQuery, null)
        if (cursor != null) {
            cursor.moveToFirst()
            do {
                var data = Data()
                data.text = cursor.getString(cursor.getColumnIndex("Text"))
                data.Image = cursor.getBlob(cursor.getColumnIndex("Image"))
            } while (cursor.moveToNext())
        }
        return OfficeList
    }

    fun getMarketData(): List<Data> {
        var MarketList = ArrayList<Data>()
        var dbHelper = writableDatabase
        val sqlQuery = "SELECT * FROM $TableMarket"
        var cursor = dbHelper.rawQuery(sqlQuery, null)
        if (cursor != null) {
            cursor.moveToFirst()
            do {
                var data = Data()
                data.text = cursor.getString(cursor.getColumnIndex("Text"))
                data.Image = cursor.getBlob(cursor.getColumnIndex("Image"))
            } while (cursor.moveToNext())
        }
        return MarketList
    }

}
  

错误

Process: com.example.muhammadrizwan.deafanddumbcommunicationaid, PID: 4181
    java.lang.IllegalStateException: activity must not be null
        at com.example.muhammadrizwan.deafanddumbcommunicationaid.Fragments.Admin_Fragment.<init>(Admin_Fragment.kt:48)
        at com.example.muhammadrizwan.deafanddumbcommunicationaid.adapter.ViewPagerAdapter.getItem(ViewPagerAdapter.kt:28)

0 个答案:

没有答案