From f3d90ae42a7ece5a9e8b597c2f9fb9a9a25cae32 Mon Sep 17 00:00:00 2001 From: Tucan444 <66880425+Tucan444@users.noreply.github.com> Date: Tue, 13 Apr 2021 09:53:32 +0200 Subject: [PATCH] more changes --- app/WikiSpot/.idea/dictionaries/ben44.xml | 1 + app/WikiSpot/app/build.gradle | 6 +- .../src/debug/res/values/google_maps_api.xml | 24 +++ app/WikiSpot/app/src/main/AndroidManifest.xml | 28 ++- .../java/com/example/wikispot/Extentions.kt | 45 ++-- .../wikispot/activities/MainActivity.kt | 175 +++++++++++---- .../wikispot/adapters/PlacePreviewsAdapter.kt | 21 +- .../wikispot/adapters/SensorsDataAdapter.kt | 44 ++++ .../wikispot/fragments/debugFragment.kt | 69 +++--- .../wikispot/fragments/homeFragment.kt | 12 +- .../wikispot/fragments/infoFragment.kt | 123 ++++++++++- .../example/wikispot/fragments/mapFragment.kt | 55 ++++- .../wikispot/modelClasses/ServerManager.kt | 62 +++++- .../modelsForAdapters/ExploreListModel.kt | 18 +- .../modelsForAdapters/SensorsListModel.kt | 30 +++ .../example/wikispot/projectScopeVariables.kt | 17 ++ .../contrasting_gradient_background.xml | 10 + .../src/main/res/layout/fragment_debug.xml | 202 +++++------------- .../app/src/main/res/layout/fragment_home.xml | 68 +++--- .../app/src/main/res/layout/fragment_info.xml | 19 +- .../app/src/main/res/layout/fragment_map.xml | 27 +-- .../main/res/layout/labeled_value_item.xml | 44 ++++ .../navigation/main_activity_navigation.xml | 23 +- .../app/src/main/res/values/colors.xml | 51 ++++- .../app/src/main/res/values/themes.xml | 68 +++--- .../release/res/values/google_maps_api.xml | 20 ++ app/WikiSpot/build.gradle | 5 +- 27 files changed, 871 insertions(+), 396 deletions(-) create mode 100644 app/WikiSpot/app/src/debug/res/values/google_maps_api.xml create mode 100644 app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/SensorsDataAdapter.kt create mode 100644 app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/SensorsListModel.kt create mode 100644 app/WikiSpot/app/src/main/res/drawable/contrasting_gradient_background.xml create mode 100644 app/WikiSpot/app/src/main/res/layout/labeled_value_item.xml create mode 100644 app/WikiSpot/app/src/release/res/values/google_maps_api.xml diff --git a/app/WikiSpot/.idea/dictionaries/ben44.xml b/app/WikiSpot/.idea/dictionaries/ben44.xml index c0e6255..27f442e 100644 --- a/app/WikiSpot/.idea/dictionaries/ben44.xml +++ b/app/WikiSpot/.idea/dictionaries/ben44.xml @@ -1,6 +1,7 @@ + backstack filetype initing diff --git a/app/WikiSpot/app/build.gradle b/app/WikiSpot/app/build.gradle index b6211fc..47735fc 100644 --- a/app/WikiSpot/app/build.gradle +++ b/app/WikiSpot/app/build.gradle @@ -2,6 +2,7 @@ plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' + id 'androidx.navigation.safeargs.kotlin' } android { @@ -35,7 +36,7 @@ android { targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { - jvmTarget = '1.8' + jvmTarget = JavaVersion.VERSION_1_8.toString() } } @@ -50,10 +51,13 @@ dependencies { implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.preference:preference:1.1.1' implementation 'com.squareup.okhttp3:okhttp:4.9.0' + implementation 'com.google.android.gms:play-services-maps:17.0.0' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation 'com.github.bumptech.glide:glide:4.12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' + + implementation 'com.github.barteksc:android-pdf-viewer:2.8.2' } \ No newline at end of file diff --git a/app/WikiSpot/app/src/debug/res/values/google_maps_api.xml b/app/WikiSpot/app/src/debug/res/values/google_maps_api.xml new file mode 100644 index 0000000..47b8de0 --- /dev/null +++ b/app/WikiSpot/app/src/debug/res/values/google_maps_api.xml @@ -0,0 +1,24 @@ + + + AIzaSyAixBio8FevppLsncIkFUQarx2kUB-0dW0 + \ No newline at end of file diff --git a/app/WikiSpot/app/src/main/AndroidManifest.xml b/app/WikiSpot/app/src/main/AndroidManifest.xml index 476e577..29b8096 100644 --- a/app/WikiSpot/app/src/main/AndroidManifest.xml +++ b/app/WikiSpot/app/src/main/AndroidManifest.xml @@ -3,9 +3,15 @@ xmlns:tools="http://schemas.android.com/tools" package="com.example.wikispot"> + + - + - + + + + + diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/Extentions.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/Extentions.kt index f0f6e8e..9b5d6f9 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/Extentions.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/Extentions.kt @@ -1,5 +1,7 @@ package com.example.wikispot +import android.app.Activity +import android.app.AlertDialog import android.content.Context import android.os.Environment import android.view.View @@ -31,38 +33,6 @@ fun Context.getThemeId(): Int { } } -// for client -fun Context.getDataFromServer(): String { - // requesting data - val url = "${ServerManagement.baseUrl}devices_list" - val request = Request.Builder().url(url).build() - val client = OkHttpClient() - var receivedResponse = "" - - client.newCall(request).enqueue(object : Callback { - override fun onResponse(call: Call, response: Response) { - response.body?.let { - receivedResponse = response.body!!.string() - } - } - - override fun onFailure(call: Call, e: IOException) { - println("Request Failed") - println(e) - } - }) - - Thread.sleep(400) - - println("[debug] received string: $receivedResponse") - try { - JSONArray(receivedResponse) - return receivedResponse - } catch (exception: Throwable) { - return "[]" - } -} - // working with files fun Context.createFile(filename: String, filetype: String): File { @@ -114,3 +84,14 @@ fun Context.getStringFromSharedPreferences(accessKey: String, preferencesFilenam return "" } + +// Activity extensions + +fun Activity.askToQuit() { + val builder = AlertDialog.Builder(this) + builder.setTitle("Confirm") + builder.setMessage("Do you want to quit the application?") + builder.setPositiveButton("Yes") { _, _ -> finish()} + builder.setNegativeButton("No") { _, _ -> } + builder.show() +} diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/activities/MainActivity.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/activities/MainActivity.kt index b7417ac..19ef4a7 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/activities/MainActivity.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/activities/MainActivity.kt @@ -3,35 +3,58 @@ package com.example.wikispot.activities import android.content.Intent import android.graphics.Bitmap import android.os.Bundle -import androidx.appcompat.app.AlertDialog +import android.util.DisplayMetrics import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController -import com.example.wikispot.IntentsKeys -import com.example.wikispot.R -import com.example.wikispot.ServerManagement +import androidx.recyclerview.widget.LinearLayoutManager +import com.example.wikispot.* +import com.example.wikispot.adapters.LabeledValuesAdapter import com.example.wikispot.fragments.* -import com.example.wikispot.getThemeId import com.example.wikispot.modelClasses.JsonManager import com.example.wikispot.modelClasses.JsonManagerLite import com.example.wikispot.modelClasses.SettingsSaveManager +import com.example.wikispot.modelsForAdapters.LabeledValue +import com.example.wikispot.modelsForAdapters.LabeledValuesSupplier import com.example.wikispot.modelsForAdapters.PlacePreview import com.example.wikispot.modelsForAdapters.PlaceSupplier +import com.google.android.gms.maps.model.LatLng import kotlinx.android.synthetic.main.activity_main.* +import kotlinx.android.synthetic.main.fragment_info.* + class MainActivity : AppCompatActivity() { override fun onBackPressed() { - val builder = AlertDialog.Builder(this) - builder.setTitle("Confirm") - builder.setMessage("Do you want to quit the application?") - builder.setPositiveButton("Yes") { _, _ -> finish()} - builder.setNegativeButton("No") { _, _ -> } - builder.show() + + try { + when (val currentlyShownFragment = mainFragmentHost.childFragmentManager.fragments[0]) { + is chatFragment -> { + askToQuit() + } + is exploreFragment -> { + askToQuit() + } + is homeFragment -> { + askToQuit() + } + is mapFragment -> { + askToQuit() + } + is settingsFragment -> { + askToQuit() + } + is infoFragment -> { + currentlyShownFragment.goExploreFragment() + } + } + } catch (e: Throwable) { println(e) } + } override fun onCreate(savedInstanceState: Bundle?) { + doPreparations() loadSettings() setTheme(getThemeId()) @@ -44,43 +67,108 @@ class MainActivity : AppCompatActivity() { handleExtras() } + private fun doPreparations() { + val displayMetrics = DisplayMetrics() + windowManager.defaultDisplay.getMetrics(displayMetrics) + ScreenParameters.height = displayMetrics.heightPixels + ScreenParameters.width = displayMetrics.widthPixels + } + override fun onResume() { super.onResume() // server communication - val dataReceiver: (String) -> Unit = {data: String -> - println("Data here: $data") + val dataReceiver0: (String) -> Unit = { data0: String -> + val dataReceiver1: (String) -> Unit = { data1: String -> + val json = JsonManager(this, data1, "JSONObject") + val names = json.currentJsonObject!!.names() + println("[debug] $data1") - try { - when (mainFragmentHost.childFragmentManager.fragments[0]) { - is chatFragment -> {} - is exploreFragment -> {} - is homeFragment -> {} - is mapFragment -> {} - is settingsFragment -> {} - } - } catch (e: Throwable) { println(e) } + try { + mainFragmentHost.childFragmentManager.fragments[0]?.let { + when (it) { + is chatFragment -> { + } + is exploreFragment -> { + } + is homeFragment -> { + LabeledValuesSupplier.wipeData() + for (n in 0 until names!!.length()) { + val labeledValue = LabeledValue(names[n].toString(), json.getAttributeContent(names[n].toString())) + if (!LabeledValuesSupplier.checkIfContains(labeledValue)) { + LabeledValuesSupplier.appendLabeledValue(labeledValue) + } + } + + it.labeled_values_recycler_view.post { + val layoutManager = LinearLayoutManager(it.requireContext()) + layoutManager.orientation = LinearLayoutManager.VERTICAL + it.labeled_values_recycler_view.layoutManager = layoutManager + + val adapter = LabeledValuesAdapter(it.requireContext(), LabeledValuesSupplier.labeledValues) + it.labeled_values_recycler_view.adapter = adapter + } + } + is mapFragment -> { + } + is settingsFragment -> { + } + is infoFragment -> { + } + else -> println("[debug] unknown fragment in sensorsConnection") + } + } + } catch (e: Throwable) { println(e) } + + } + println(data0) + + if (!ServerManagement.serverManager.checkIfConnectionAlreadyExists("sensorsConnection")){ + ServerManagement.serverManager.addReceiverConnection(dataReceiver1, this, "sensorsConnection", data0.toInt(), ServerManagement.sensors_keyword) + } + + // getting other needed information + val dataReceiver2: (String) -> Unit = {data1: String -> + var json = JsonManager(this, data1) + json = JsonManager(this, json.findJsonObjectByAttribute("ID", data0.toInt()), "JSONObject") + val positionsList = json.getAttributeContent("location").split(",") + MapManagement.connectedServerTitle = json.getAttributeContentByPath("description/title") + MapManagement.connectedServerPosition = LatLng(positionsList[0].toDouble(), positionsList[1].toDouble()) + } + + if (!ServerManagement.serverManager.checkIfConnectionAlreadyExists("mapConnection")){ + ServerManagement.serverManager.addReceiverConnection(dataReceiver2, this, "mapConnection", data0.toInt(), "", "GET_WHOLE_ARRAY") + } } - ServerManagement.serverManager.addReceiverConnection(dataReceiver, this, "mainConnection", 0, "test0.json") + ServerManagement.serverManager.getData(dataReceiver0, this, 0, "", "connected_id", 3) connectExploreFragmentAdapterModel() } override fun onPause() { PlaceSupplier.saveToCache(this) - ServerManagement.serverManager.deleteConnection("mainConnection") + ServerManagement.serverManager.deleteConnection("sensorsConnection") + ServerManagement.serverManager.deleteConnection("mapConnection") ServerManagement.serverManager.deleteConnection("exploreListConnection") super.onPause() } private fun handleExtras() { when (intent.getStringExtra(IntentsKeys.startFragment)) { - "chatFragment" -> {mainBottomNavigationView.selectedItemId = R.id.chatFragment} - "exploreFragment" -> {mainBottomNavigationView.selectedItemId = R.id.exploreFragment} + "chatFragment" -> { + mainBottomNavigationView.selectedItemId = R.id.chatFragment + } + "exploreFragment" -> { + mainBottomNavigationView.selectedItemId = R.id.exploreFragment + } // skipping home fragment because were already here - "mapFragment" -> {mainBottomNavigationView.selectedItemId = R.id.mapFragment} - "settingsFragment" -> {mainBottomNavigationView.selectedItemId = R.id.settingsFragment} + "mapFragment" -> { + mainBottomNavigationView.selectedItemId = R.id.mapFragment + } + "settingsFragment" -> { + mainBottomNavigationView.selectedItemId = R.id.settingsFragment + } } } @@ -95,25 +183,26 @@ class MainActivity : AppCompatActivity() { PlaceSupplier.loadFromCache(this) // connecting to server - val dataReceiver: (String) -> Unit = {data: String -> + val dataReceiver: (String) -> Unit = { data: String -> val json = JsonManager(this, data) if (PlaceSupplier.controlJson == null) { PlaceSupplier.controlJson = JsonManagerLite(data) } - for (i in 1 until json.getLengthOfJsonArray()) { // todo change to 1 + for (i in 1 until json.getLengthOfJsonArray()) { json.getJsonObject(i) val id = json.getAttributeContent("ID").toInt() + val location = json.getAttributeContent("location") json.getAttributeContent("description") val title = json.getAttributeContent("title") val shortDescription = json.getAttributeContent("description_s") - val place = PlacePreview(title, shortDescription, null, id) + val place = PlacePreview(title, shortDescription, location, null, id) if (!PlaceSupplier.checkIfContains(place)) { - val imageReceiver: (Bitmap) -> Unit = {bitmap: Bitmap -> + val imageReceiver: (Bitmap) -> Unit = { bitmap: Bitmap -> place.img = bitmap } @@ -123,7 +212,7 @@ class MainActivity : AppCompatActivity() { } else { val containingPlace = PlaceSupplier.getContainingInstance(place) if ((containingPlace != null) and (containingPlace?.img == null)) { - val imageReceiver: (Bitmap) -> Unit = {bitmap: Bitmap -> + val imageReceiver: (Bitmap) -> Unit = { bitmap: Bitmap -> containingPlace?.img = bitmap } @@ -145,11 +234,21 @@ class MainActivity : AppCompatActivity() { try { when (mainFragmentHost.childFragmentManager.fragments[0]) { - is chatFragment -> {currentNavHostFragmentName = "chatFragment"} - is exploreFragment -> {currentNavHostFragmentName= "exploreFragment"} - is homeFragment -> {currentNavHostFragmentName = "homeFragment"} - is mapFragment -> {currentNavHostFragmentName = "mapFragment"} - is settingsFragment -> {currentNavHostFragmentName = "settingsFragment"} + is chatFragment -> { + currentNavHostFragmentName = "chatFragment" + } + is exploreFragment -> { + currentNavHostFragmentName = "exploreFragment" + } + is homeFragment -> { + currentNavHostFragmentName = "homeFragment" + } + is mapFragment -> { + currentNavHostFragmentName = "mapFragment" + } + is settingsFragment -> { + currentNavHostFragmentName = "settingsFragment" + } } } catch (e: Throwable) { println(e) } diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/PlacePreviewsAdapter.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/PlacePreviewsAdapter.kt index dba3e0e..093ee15 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/PlacePreviewsAdapter.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/PlacePreviewsAdapter.kt @@ -8,8 +8,10 @@ import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import com.example.wikispot.R import com.example.wikispot.ServerManagement +import com.example.wikispot.fragments.exploreFragmentDirections import com.example.wikispot.modelsForAdapters.PlacePreview import com.example.wikispot.showToast +import com.google.android.gms.maps.model.LatLng import kotlinx.android.synthetic.main.explore_list_item.view.* @@ -19,11 +21,20 @@ class PlacePreviewsAdapter(private val context: Context, private val placePrevie var currentPlacePreview: PlacePreview? = null var pos: Int = 0 + var location: LatLng? = null init { itemView.setOnClickListener { ServerManagement.selectedServerId = currentPlacePreview?.id!! - Navigation.findNavController(it).navigate(R.id.navigateToInfoFragment) + val action = exploreFragmentDirections.navigateToInfoFragment(true) + Navigation.findNavController(it).navigate(action) + } + + itemView.item_location_img.setOnClickListener { + if (location != null) { + val action = exploreFragmentDirections.navigateToMapFragment(location!!, currentPlacePreview!!.title) + Navigation.findNavController(it).navigate(action) + } } } @@ -31,6 +42,14 @@ class PlacePreviewsAdapter(private val context: Context, private val placePrevie placePreview?.let { itemView.item_title.text = placePreview.title itemView.item_description.text = placePreview.description + + try { + val coordinates = placePreview.location!!.split(",") + location = LatLng(coordinates[0].toDouble(), coordinates[1].toDouble()) + } catch (e: Throwable) { + println("[debug] Failed getting coordinates in ${placePreview.title}, explore fragment list. Exception: $e")} + + placePreview.img?.let { itemView.item_img.setImageBitmap(placePreview.img) } diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/SensorsDataAdapter.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/SensorsDataAdapter.kt new file mode 100644 index 0000000..96b1269 --- /dev/null +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/adapters/SensorsDataAdapter.kt @@ -0,0 +1,44 @@ +package com.example.wikispot.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import com.example.wikispot.R +import com.example.wikispot.modelsForAdapters.LabeledValue +import kotlinx.android.synthetic.main.labeled_value_item.view.* + + +class LabeledValuesAdapter(private val context: Context, private val labeledValues: Array) : RecyclerView.Adapter() { + + inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){ + + var currentLabeledValue: LabeledValue? = null + var pos: Int = 0 + + fun setData(labeledValue: LabeledValue?, pos: Int) { + labeledValue?.let { + itemView.label.text = labeledValue.label + itemView.value.text = labeledValue.value + } + + this.currentLabeledValue = labeledValue + this.pos = pos + } + } + + override fun onBindViewHolder(holder: MyViewHolder, position: Int) { + val labeledValue = labeledValues[position] + holder.setData(labeledValue, position) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { + val view = LayoutInflater.from(context).inflate(R.layout.labeled_value_item, parent, false) + return MyViewHolder(view) + } + + override fun getItemCount(): Int { + return labeledValues.size + } +} diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/debugFragment.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/debugFragment.kt index b458d39..474f151 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/debugFragment.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/debugFragment.kt @@ -1,12 +1,15 @@ package com.example.wikispot.fragments import android.annotation.SuppressLint +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.net.Uri import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.navigation.Navigation import com.example.wikispot.R -import com.example.wikispot.getDataFromServer +import com.example.wikispot.ServerManagement import com.example.wikispot.modelClasses.JsonManager import kotlinx.android.synthetic.main.fragment_debug.* @@ -19,39 +22,41 @@ class debugFragment : Fragment(R.layout.fragment_debug) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - getDataBtn.setOnClickListener { - context?.let { - jsonManager = JsonManager(requireContext(), requireContext().getDataFromServer(), "JSONArray", true) - sizeView.text = jsonManager.getLengthOfJsonArray().toString() - } - } - - getJsonFileBtn.setOnClickListener { - val id = idInput.text.toString().toInt() - jsonFileContentView.text = jsonManager.getJsonObject(id).toString() - } - - getAttributeContentBtn.setOnClickListener { - val attributeName = attributeNameInput.text.toString() - if ("/" in attributeName) { - attributeContentView.text = jsonManager.getAttributeContentByPath(attributeNameInput.text.toString()) - } else { - attributeContentView.text = jsonManager.getAttributeContent(attributeNameInput.text.toString()) - } - } - - clearAttributeBtn.setOnClickListener { - jsonManager.clearSelectedAttribute() - attributeContentView.text = "attribute content" - } - - attributeNameInput.setOnClickListener { - attributeContentView.text = jsonManager.getCurrentJsonAttributeContent() - } - - // handling navigation between debug fragments goSecondDebugFragmentBtn.setOnClickListener { Navigation.findNavController(it).navigate(R.id.navigateToAnotherDebugFragment) } + + getNumberOfSentRequestsBtn.setOnClickListener { + outputText.text = ServerManagement.totalNumberOfRequestsSent.toString() + } + + val pdfRequestThread = Thread(PdfRequest()) + pdfRequestThread.start() + + + + } + + inner class PdfRequest : Runnable { + + override fun run() { + val inputStream = java.net.URL("${ServerManagement.baseUrl}files/1/sample.pdf").openStream() + val uri = Uri.parse("${ServerManagement.baseUrl}files/1/sample.pdf") + + Thread.sleep(500) + + pdfView.post { + println("asdfsdfsdfs") + //pdfView.fromUri(uri).load() + pdfView.fromStream(inputStream).pages(0).load() + pdfView.zoomTo(pdfView.width / 490.0F) + println("[debug] zoom is ${pdfView.width / 490.0F}") + println(pdfView.width) + Thread.sleep(1000) + println(pdfView.currentPage) + } + + ServerManagement.totalNumberOfRequestsSent += 1 + } } } \ No newline at end of file diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/homeFragment.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/homeFragment.kt index 532e7ee..7b19155 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/homeFragment.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/homeFragment.kt @@ -1,5 +1,6 @@ package com.example.wikispot.fragments +import android.graphics.Bitmap import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment @@ -39,11 +40,20 @@ class homeFragment : Fragment(R.layout.fragment_home) { fragment.mainDescription.text = json.getAttributeContentByPath("description/description_l") } } + + val imageReceiver: (Bitmap) -> Unit = { bitmap: Bitmap -> + homeFragmentInnerFragment.post { + homeFragmentInnerFragment.mainImage.setImageBitmap(bitmap) + } + } + + ServerManagement.serverManager.getImage(imageReceiver, json.getAttributeContent("ID").toInt(), "test0.jpg", 3) + } } catch (e: Throwable) { println(e) } } - ServerManagement.serverManager.getData(dataReceiver, requireContext(), 0, "", "GET_JSON_ARRAY", 3) + ServerManagement.serverManager.getData(dataReceiver, requireContext(), 0, "", "GET_WHOLE_ARRAY", 3) } diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/infoFragment.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/infoFragment.kt index 4ee6039..65f87d9 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/infoFragment.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/infoFragment.kt @@ -1,19 +1,134 @@ package com.example.wikispot.fragments +import android.graphics.Bitmap import android.os.Bundle -import androidx.fragment.app.Fragment -import android.view.LayoutInflater import android.view.View -import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.navigation.Navigation +import androidx.navigation.fragment.navArgs +import androidx.recyclerview.widget.LinearLayoutManager import com.example.wikispot.R +import com.example.wikispot.ServerManagement +import com.example.wikispot.adapters.LabeledValuesAdapter import com.example.wikispot.modelClasses.JsonManager +import com.example.wikispot.modelsForAdapters.LabeledValue +import com.example.wikispot.modelsForAdapters.LabeledValuesSupplier +import com.google.android.gms.maps.model.LatLng import kotlinx.android.synthetic.main.fragment_info.* class infoFragment() : Fragment(R.layout.fragment_info) { + private val args: infoFragmentArgs by navArgs() + var location: LatLng? = null + var loadAutomatically = false + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + + updateRecyclerView() + + try { + loadAutomatically = args.loadAutomatically + } catch (e: Throwable) { println("[debug] Exception in Info Fragment while getting args: $e") } + + if (loadAutomatically) { + load() + } + + locationBtn.setOnClickListener { + if (loadAutomatically) { + if (location != null) { + val action = infoFragmentDirections.infoFragmentToMapFragment(location!!, mainTitle.text.toString()) + Navigation.findNavController(it).navigate(action) + } + } else { + Navigation.findNavController(it).navigate(R.id.homeFragment_to_mapFragment) + } + } } -} \ No newline at end of file + private fun load() { + val serverId = ServerManagement.selectedServerId + + val dataReceiver: (String) -> Unit = { data: String -> + try { + context?.let { + val json = JsonManager(requireContext(), data) + json.findJsonObjectByAttribute("ID", serverId) + + mainTitle.post { + mainTitle.text = json.getAttributeContentByPath("description/title") + } + mainDescription.post { + this.mainDescription.text = json.getAttributeContentByPath("description/description_s") + } + + val imageReceiver: (Bitmap) -> Unit = { bitmap: Bitmap -> + mainImage.post { + mainImage?.let { + mainImage.setImageBitmap(bitmap) + } + } + } + + val coordinates = json.getAttributeContent("location").split(",") + location = LatLng(coordinates[0].toDouble(), coordinates[1].toDouble()) + + ServerManagement.serverManager.getImage(imageReceiver, json.getAttributeContent("ID").toInt(), "test0.jpg", 2) + } + } catch (e: Throwable) { println(e) } + } + + val sensorsDataReceiver: (String) -> Unit = {data: String -> + try { + context?.let { + println("[debug][info fragment] $data") + val json = JsonManager(requireContext(), data, "JSONObject") + val names = json.currentJsonObject!!.names() + + LabeledValuesSupplier.wipeData() + + for (n in 0 until names!!.length()) { + val labeledValue = LabeledValue(names[n].toString(), json.getAttributeContent(names[n].toString())) + if (!LabeledValuesSupplier.checkIfContains(labeledValue)) { + LabeledValuesSupplier.appendLabeledValue(labeledValue) + } + } + + updateRecyclerView() + } + } catch (e: Throwable) { println(e) } + } + + context?.let { + ServerManagement.serverManager.getData(dataReceiver, requireContext(), serverId, "", "GET_WHOLE_ARRAY") + ServerManagement.serverManager.addReceiverConnection(sensorsDataReceiver, requireContext(), "infoFragmentSensorsConnection", + serverId, ServerManagement.sensors_keyword) + } + + } + + override fun onPause() { + ServerManagement.serverManager.deleteConnection("infoFragmentSensorsConnection") + super.onPause() + } + + private fun updateRecyclerView() { + + labeled_values_recycler_view.post { + val layoutManager = LinearLayoutManager(context) + layoutManager.orientation = LinearLayoutManager.VERTICAL + labeled_values_recycler_view.layoutManager = layoutManager + + val adapter = context?.let { LabeledValuesAdapter(it, LabeledValuesSupplier.labeledValues) } + labeled_values_recycler_view.adapter = adapter + } + + } + + fun goExploreFragment() { + Navigation.findNavController(mainTitle).navigate(R.id.navigateBackToExploreFragment) + } + +} diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/mapFragment.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/mapFragment.kt index cb87847..7e842d4 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/mapFragment.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/fragments/mapFragment.kt @@ -1,12 +1,63 @@ package com.example.wikispot.fragments import android.os.Bundle -import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.navigation.fragment.navArgs +import com.example.wikispot.MapManagement import com.example.wikispot.R +import com.google.android.gms.maps.CameraUpdateFactory +import com.google.android.gms.maps.OnMapReadyCallback +import com.google.android.gms.maps.SupportMapFragment +import com.google.android.gms.maps.model.LatLng +import com.google.android.gms.maps.model.MarkerOptions +class mapFragment : Fragment() { -class mapFragment : Fragment(R.layout.fragment_map) { + val args: mapFragmentArgs by navArgs() + private var loadFromMapManager = true + var location: LatLng? = null + var markerTitle: String? = null + + private val callback = OnMapReadyCallback { googleMap -> + /** + * Manipulates the map once available. + * This callback is triggered when the map is ready to be used. + * This is where we can add markers or lines, add listeners or move the camera. + * In this case, we just add a marker near Sydney, Australia. + * If Google Play services is not installed on the device, the user will be prompted to + * install it inside the SupportMapFragment. This method will only be triggered once the + * user has installed Google Play services and returned to the app. + */ + /*val pb = LatLng(49.11274928646463, 18.443442353021045) + googleMap.addMarker(MarkerOptions().position(pb).title("Povazska Bystrica")) + googleMap.moveCamera(CameraUpdateFactory.newLatLng(pb)) + googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pb, 16.0f)) */ + + try { + location = args.location + markerTitle = args.markerTitle + loadFromMapManager = false + } catch (e: Throwable) { println("[debug] Exception in Map Fragment while getting args: $e") } + + if (loadFromMapManager) { + googleMap.addMarker(MarkerOptions().position(MapManagement.connectedServerPosition!!).title(MapManagement.connectedServerTitle)) + googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(MapManagement.connectedServerPosition, 16.0F)) + } else { + googleMap.addMarker(MarkerOptions().position(location!!).title(markerTitle)) + googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 16.0F)) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_map, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment? + mapFragment?.getMapAsync(callback) + } } \ No newline at end of file diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/modelClasses/ServerManager.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/modelClasses/ServerManager.kt index e89656d..6093ded 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/modelClasses/ServerManager.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/modelClasses/ServerManager.kt @@ -16,6 +16,8 @@ class ServerManager { private var receiverConnections = mutableListOf() private var viewConnections = mutableListOf() + // single time requests + fun getData(dataReceiver: (String) -> Unit, context: Context, serverId: Int, path: String, attributePath: String="", numberOfAttempts: Int=2) { val dataRequestThread = Thread(DataRequest(dataReceiver, context, serverId, path, attributePath, numberOfAttempts)) dataRequestThread.start() @@ -27,7 +29,11 @@ class ServerManager { var url = "${ServerManagement.baseUrl}devices_list" if (path != "") { - url = "${ServerManagement.baseUrl}files/$serverId/$path" + if (path.contains(ServerManagement.sensors_keyword)){ + url = "${ServerManagement.baseUrl}$serverId/sensors" + } else { + url = "${ServerManagement.baseUrl}files/$serverId/$path" + } } val request = Request.Builder().url(url).build() @@ -46,11 +52,11 @@ class ServerManager { val jsonManager = JsonManager(context, receivedString) if (path == "") { - if (attributePath == "GET_JSON_ARRAY") { + if (attributePath == "GET_WHOLE_ARRAY") { dataReceiver(jsonManager.jsonArray.toString()) return } - jsonManager.getJsonObject(serverId) + jsonManager.getJsonObject(0) } else { if (attributePath == "") { throw Throwable() @@ -88,6 +94,8 @@ class ServerManager { } }) + ServerManagement.totalNumberOfRequestsSent += 1 + Thread.sleep(ServerManagement.dataRequestOnAttemptWait) } } @@ -110,6 +118,8 @@ class ServerManager { imageReceiver(bitmap) } catch (e: Throwable) { println(e) } + ServerManagement.totalNumberOfRequestsSent += 1 + Thread.sleep(ServerManagement.imageRequestOnAttemptWait) } } @@ -132,8 +142,27 @@ class ServerManager { } } + fun checkIfConnectionAlreadyExists(connectionName: String, connectionType: String="any"): Boolean{ + if ((connectionType == "any") or (connectionType == "receiver")) { + for (n in 0 until receiverConnections.size) { + if (receiverConnections[n].connectionName == connectionName) { + return true + } + } + } + if ((connectionType == "any") or (connectionType == "view")) { + for (n in 0 until viewConnections.size) { + if (viewConnections[n].connectionName == connectionName) { + return true + } + } + } + + return false + } + fun deleteConnection(connectionName: String, connectionType: String="any") { // other types are any, activity and view - if ((connectionType == "any") or (connectionType == "activity")) { + if ((connectionType == "any") or (connectionType == "receiver")) { for (i in 0 until receiverConnections.size) { // checking in connections try { if (receiverConnections[i].connectionName == connectionName) { @@ -156,11 +185,11 @@ class ServerManager { } } - fun addReceiverConnection(dataReceiver: (String) -> Unit, context: Context, connectionName: String, serverId: Int, path: String?=null, attributePath: String="", waitTime: Long=ServerManagement.receiverConnectionOnCheckWait) { + fun addReceiverConnection(dataReceiver: (String) -> Unit, context: Context, connectionName: String, serverId: Int, path: String="", attributePath: String="", waitTime: Long=ServerManagement.receiverConnectionOnCheckWait) { receiverConnections.add(ReceiverConnection(dataReceiver, context, connectionName, serverId, path, attributePath, waitTime)) } - inner class ReceiverConnection(val dataReceiver: (String) -> Unit, val context: Context, val connectionName: String, val serverId: Int, val path: String?=null, val attributePath: String, val waitTime: Long) { + inner class ReceiverConnection(val dataReceiver: (String) -> Unit, val context: Context, val connectionName: String, val serverId: Int, val path: String="", val attributePath: String, val waitTime: Long) { var running = true @@ -175,7 +204,11 @@ class ServerManager { var url = "${ServerManagement.baseUrl}devices_list" if (path != "") { - url = "${ServerManagement.baseUrl}files/$serverId/$path" + if (path.contains(ServerManagement.sensors_keyword)){ + url = "${ServerManagement.baseUrl}$serverId/sensors" + } else { + url = "${ServerManagement.baseUrl}files/$serverId/$path" + } } val request = Request.Builder().url(url).build() @@ -198,7 +231,7 @@ class ServerManager { dataReceiver(jsonManager.jsonArray.toString()) return } - jsonManager.getJsonObject(serverId) + jsonManager.getJsonObject(0) } else { if (attributePath == "") { throw Throwable() @@ -236,6 +269,8 @@ class ServerManager { } }) + ServerManagement.totalNumberOfRequestsSent += 1 + Thread.sleep(waitTime) } } @@ -262,7 +297,11 @@ class ServerManager { var url = "${ServerManagement.baseUrl}devices_list" if (path != "") { - url = "${ServerManagement.baseUrl}files/$serverId/$path" + if (path.contains(ServerManagement.sensors_keyword)){ + url = "${ServerManagement.baseUrl}$serverId/sensors" + } else { + url = "${ServerManagement.baseUrl}files/$serverId/$path" + } } val request = Request.Builder().url(url).build() @@ -286,7 +325,7 @@ class ServerManager { view.text = jsonManager.jsonArray.toString() return } - jsonManager.getJsonObject(serverId) + jsonManager.getJsonObject(0) } else { if (attributePath == "") { throw Throwable() @@ -333,6 +372,9 @@ class ServerManager { println(e) } }) + + ServerManagement.totalNumberOfRequestsSent += 1 + Thread.sleep(ServerManagement.viewConnectionOnCheckWait) } } diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/ExploreListModel.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/ExploreListModel.kt index e11ecd1..d581a34 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/ExploreListModel.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/ExploreListModel.kt @@ -3,13 +3,15 @@ package com.example.wikispot.modelsForAdapters import android.content.Context import android.graphics.Bitmap import android.media.Image +import com.example.wikispot.ScreenParameters import com.example.wikispot.getStringFromSharedPreferences import com.example.wikispot.modelClasses.JsonManager import com.example.wikispot.modelClasses.JsonManagerLite import com.example.wikispot.saveString +import com.google.android.gms.maps.model.LatLng import org.json.JSONArray -data class PlacePreview(var title: String, var description: String, var img: Bitmap? = null, val id: Int?=null) { +data class PlacePreview(var title: String, var description: String, val location: String? = null, var img: Bitmap? = null, val id: Int?=null) { init { val words = description.split(" ") @@ -80,7 +82,7 @@ object PlaceSupplier { val jsonManager = JsonManager(context, save) for (n in 0 until jsonManager.getLengthOfJsonArray()) { val savedData = jsonManager.jsonArray?.get(n).toString().split("|||||") - val place = PlacePreview(savedData[0], savedData[1], null, savedData[2].toInt()) + val place = PlacePreview(savedData[0], savedData[1], savedData[2], null, savedData[3].toInt()) if (!checkIfContains(place)) { appendPlace(place) } @@ -93,10 +95,9 @@ object PlaceSupplier { for (n in places.indices) { val place = places[n] if (getSavePermission(place)) { - save.put(n, "${place!!.title}|||||${place.description}|||||${place.id}") + save.put(n, "${place!!.title}|||||${place.description}|||||${place.location}|||||${place.id}") } } - //save.put("hi|||||sdhsiujdghsiuy|||||45") context.saveString("placePreviews", save.toString(), "exploreFragmentCache") } @@ -111,9 +112,12 @@ object PlaceSupplier { controlJson!!.getJsonObject(n) if (place.id == controlJson!!.getAttributeContent("ID").toInt()) { if (place.title == controlJson!!.getAttributeContentByPath("description/title")) { - val tempPlace = PlacePreview("", controlJson!!.getAttributeContentByPath("description/description_s")) + val tempPlace = PlacePreview("", controlJson!!.getAttributeContentByPath("description/description_s"), + controlJson!!.getAttributeContentByPath("location")) if (place.description == tempPlace.description) { - return true + if (place.location == tempPlace.location) { + return true + } } } } @@ -123,4 +127,4 @@ object PlaceSupplier { return false } -} \ No newline at end of file +} diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/SensorsListModel.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/SensorsListModel.kt new file mode 100644 index 0000000..1949851 --- /dev/null +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/modelsForAdapters/SensorsListModel.kt @@ -0,0 +1,30 @@ +package com.example.wikispot.modelsForAdapters + +data class LabeledValue(val label: String, val value: String) + + +object LabeledValuesSupplier { + + var labeledValues = arrayOf() + + fun appendLabeledValue(labeledValue: LabeledValue) { + val array = labeledValues.copyOf(labeledValues.size + 1) + array[labeledValues.size] = labeledValue + labeledValues = array + } + + fun checkIfContains(labeledValue: LabeledValue): Boolean{ + for (n in labeledValues.indices) { + if (labeledValues[n]!!.label == labeledValue.label) { + return true + } + } + return false + } + + fun wipeData() { + labeledValues = arrayOf() + } + +} + diff --git a/app/WikiSpot/app/src/main/java/com/example/wikispot/projectScopeVariables.kt b/app/WikiSpot/app/src/main/java/com/example/wikispot/projectScopeVariables.kt index b0aaf09..9dc0c24 100644 --- a/app/WikiSpot/app/src/main/java/com/example/wikispot/projectScopeVariables.kt +++ b/app/WikiSpot/app/src/main/java/com/example/wikispot/projectScopeVariables.kt @@ -1,6 +1,8 @@ package com.example.wikispot +import android.util.DisplayMetrics import com.example.wikispot.modelClasses.ServerManager +import com.google.android.gms.maps.model.LatLng object GeneralVariables { @@ -24,6 +26,21 @@ object ServerManagement { const val imageRequestOnAttemptWait: Long = 2000 const val baseUrl = "http://192.168.1.230:8000/" var selectedServerId = 0 + + const val sensors_keyword = "_[{(S,e,n,s,o,r,s)}]_" + + var totalNumberOfRequestsSent = 0 +} + +object MapManagement { + var connectedServerPosition: LatLng? = null + var connectedServerTitle: String? = null +} + + +object ScreenParameters { + var height = 1 + var width = 1 } diff --git a/app/WikiSpot/app/src/main/res/drawable/contrasting_gradient_background.xml b/app/WikiSpot/app/src/main/res/drawable/contrasting_gradient_background.xml new file mode 100644 index 0000000..623cbcd --- /dev/null +++ b/app/WikiSpot/app/src/main/res/drawable/contrasting_gradient_background.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/app/WikiSpot/app/src/main/res/layout/fragment_debug.xml b/app/WikiSpot/app/src/main/res/layout/fragment_debug.xml index 0e2ef5b..39982a6 100644 --- a/app/WikiSpot/app/src/main/res/layout/fragment_debug.xml +++ b/app/WikiSpot/app/src/main/res/layout/fragment_debug.xml @@ -4,163 +4,65 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" - android:background="#EF5350" + android:background="#E35050" tools:context=".fragments.debugFragment"> - - -