Untitled
raw download clone
TEXT
views 20
,
size 12208 b
package com.realdolmen.wasdappgroepb.wasdapp.activities

import android.content.DialogInterface
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Patterns
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.gms.maps.model.LatLng
import com.google.gson.GsonBuilder
import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.integration.android.IntentResult
import com.realdolmen.wasdappgroepb.wasdapp.R
import com.realdolmen.wasdappgroepb.wasdapp.dataclasses.WasdappEntry
import com.realdolmen.wasdappgroepb.wasdapp.dataclasses.WasdappEntryBuilder
import com.realdolmen.wasdappgroepb.wasdapp.repo.WasdappRepo
import kotlinx.android.synthetic.main.activity_insert.*
import kotlinx.android.synthetic.main.app_bar_insert.*
import kotlinx.android.synthetic.main.content_insert.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception

class Insert : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener{
    var scannedResult: String = ""
    var id: Long? = null
    private var geo:LatLng?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_insert)

        var button = findViewById<Button>(R.id.btn_insertData)
        button.setOnClickListener {
            val address =
                ed_street.text.toString() + " " + ed_number.text.toString() + " " + ed_city.text.toString() + " " + ed_postalcode.toString()
            geo= getLocationFromAddress(address)
            insert()
        }
        if (intent.extras != null) {
            id = intent.getLongExtra("idEntry", 0)
            setContentEdit(id!!)
        }
        setDrawer()
    }

    private fun setupRepo(): WasdappRepo {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl("http://wp1697:8080/wasdappentry/").build()
            .create(WasdappRepo::class.java)
    }

    private fun insert() {

        var entry = WasdappEntryBuilder()
            .setName(ed_name.text.toString())
            .setEmail(ed_email.text.toString())
            .setTel(ed_phone.text.toString())
            .setStreet(ed_street.text.toString())
            .setNumber(ed_number.text.toString())
            .setPostcode(ed_postalcode.text.toString())
            .setCity(ed_city.text.toString())
            .setWiki(ed_wiki.text.toString())
            .setWeb(ed_website.text.toString())
            .setDescription(ed_description.text.toString())

        if (id != null) {
            entry = entry.setId(id!!)
        }

        if (controle(entry) != null) {

            var repo = setupRepo()
            var wassdapActual = controle(entry)?.let { repo.insert(it) }
            wassdapActual?.enqueue(object : Callback<Boolean> {
                override fun onFailure(call: Call<Boolean>, t: Throwable) {
                    println(t.message)
                }

                override fun onResponse(call: Call<Boolean>, response: Response<Boolean>) {
                    val i = Intent(this@Insert, Homepage::class.java)

                    var toastText = "${controle(entry)?.name}' has been added to the database."
                    if (id != null) {
                        toastText = "The changes to '${controle(entry)?.name}' have been saved."
                    }
                    Toast.makeText(
                        this@Insert,
                        toastText,
                        Toast.LENGTH_SHORT
                    ).show()
                    startActivity(i)
                }
            })
        }
    }

    private fun controle(wasdappEntry: WasdappEntryBuilder): WasdappEntry? {



        if (ed_name.text.toString().length > 20 || ed_name.text.trim().isEmpty()) {
            ed_name.error = "max 20 numbers and not empty"
            ed_name.requestFocus()
            return null
        }
        if (ed_email.text.trim().isEmpty()) {
            wasdappEntry.setEmail(null)
        } else if (!Patterns.EMAIL_ADDRESS.matcher(ed_email.text.toString()).matches()) {
            ed_email.error = "Please use correct Email"
            ed_email.requestFocus()
            return null
        }

        if (ed_phone.text.trim().isEmpty()) {
            wasdappEntry.setTel(null)
        }
        if (ed_street.text.trim().isEmpty()) {
            wasdappEntry.setStreet(null)
            wasdappEntry.setLat(null)
            wasdappEntry.setLon(null)
        }
        if (ed_number.text.trim().isEmpty()) {
            wasdappEntry.setNumber(null)
        }
        if (ed_postalcode.text.length > 4) {
            ed_postalcode.error = "max 4 numbers "
            ed_postalcode.requestFocus()
            return null
        }
        if (ed_city.text.trim().isEmpty()) {
            wasdappEntry.setCity(null)
        }
        if (ed_wiki.text.trim().isEmpty()) {
            wasdappEntry.setWiki(null)
        }
        if (ed_website.text.trim().isEmpty()) {
            wasdappEntry.setWeb(null)
        }
        if (ed_description.text.trim().isEmpty()) {
            wasdappEntry.setDescription(null)
        }
        if (geo == null) {
            println(geo)
            Toast.makeText(this, "address not found", Toast.LENGTH_SHORT).show()
            ed_street.error = "Address was not found"
            ed_street.requestFocus()
            return null
        } else {
            println(geo)
            wasdappEntry.setLon(geo?.longitude)
            wasdappEntry.setLat(geo?.latitude)
        }

        return wasdappEntry.build()
    }

    private fun setContentEdit(id: Long) {
        btn_insertData.text = "EDIT"
        title = "Edit"
        var repo = setupRepo()
        var call = repo.getOne(id)
        call.enqueue(object : Callback<WasdappEntry> {
            override fun onResponse(call: Call<WasdappEntry>, response: Response<WasdappEntry>) {
                if (response.code() == 200) {
                    var entryToEdit = response.body()!!
                    var name = findViewById<EditText>(R.id.ed_name)
                    var email = findViewById<EditText>(R.id.ed_email)
                    var phone = findViewById<EditText>(R.id.ed_phone)
                    var street = findViewById<EditText>(R.id.ed_street)
                    var streetNumber = findViewById<EditText>(R.id.ed_number)
                    var postalCode = findViewById<EditText>(R.id.ed_postalcode)
                    var city = findViewById<EditText>(R.id.ed_city)
                    var wiki = findViewById<EditText>(R.id.ed_wiki)
                    var website = findViewById<EditText>(R.id.ed_website)
                    var description = findViewById<EditText>(R.id.ed_description)
                    name.setText(entryToEdit.name)
                    email.setText(entryToEdit.email)
                    phone.setText(entryToEdit.tel)
                    street.setText(entryToEdit.street)
                    streetNumber.setText(entryToEdit.number)
                    postalCode.setText(entryToEdit.postcode)
                    city.setText(entryToEdit.city)
                    wiki.setText(entryToEdit.wiki)
                    website.setText(entryToEdit.web)
                    description.setText(entryToEdit.description)
                }
            }

            override fun onFailure(call: Call<WasdappEntry>, t: Throwable) {
                println(t.toString())
            }
        })


    }

    private fun setDrawer() {
        setSupportActionBar(toolbarInsert)
        val toggle = ActionBarDrawerToggle(
            this, drawer_layout_insert, toolbarInsert,
            R.string.navigation_drawer_open,
            R.string.navigation_drawer_close
        )
        drawer_layout_insert.addDrawerListener(toggle)
        toggle.syncState()
        nav_viewInsert.setNavigationItemSelectedListener(this)
    }

    override fun onBackPressed() {
        if (drawer_layout_insert.isDrawerOpen(GravityCompat.START)) {
            drawer_layout_insert.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.insert, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_addUser -> {
                val intent = Intent(this, AddUser::class.java)
                intent.action = Intent.ACTION_SEND
                startActivity(intent)
            }
            R.id.nav_addRecord -> {
                val intent = Intent(this, Insert::class.java)
                startActivity(intent)
            }
            R.id.nav_scanCode -> {
                IntentIntegrator(this@Insert).initiateScan()
            }
            R.id.nav_viewRecord -> {
                val intent = Intent(this, Homepage::class.java)
                intent.action = Intent.ACTION_SEND
                startActivity(intent)
            }
            R.id.nav_logOut -> {
                val intent = Intent(this, Login::class.java)
                intent.action = Intent.ACTION_SEND
                startActivity(intent)
            }
        }
        drawer_layout_insert.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        var result: IntentResult? = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)

        if (result != null) {

            scannedResult = result.contents
            if (scannedResult.toLongOrNull() != null) {
                val intent = Intent(this, WasdappDetailPage::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.putExtra("idEntry", scannedResult.toLong())
                this.startActivity(intent)
            } else {
                val saveAlert = AlertDialog.Builder(this)
                saveAlert.setTitle("Scan Error")
                saveAlert.setMessage("QR code did not contain a number!")
                saveAlert.setPositiveButton("OK") { dialogInterface: DialogInterface, i: Int ->
                    dialogInterface.dismiss()
                }
                saveAlert.show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun getLocationFromAddress(strAddress: String): LatLng? {

        var coder = Geocoder(this)
        var address: List<Address>?
        var p1: LatLng? = null

        try {
            address = coder.getFromLocationName(strAddress, 5)
            if (address == null) {
                return null
            }

            var location: Address = address[0]
            p1 = LatLng(location.latitude, location.longitude)

        } catch (e: Exception) {
            println(e.message)
        }


        return p1
    }

}
close fullscreen
Login or Register to edit or fork this paste. It's free.