How can I update seekBar by seconds on Media Player?(kotlin) - function

package com.example.ebookactivity
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.ebookactivity.databinding.FragmentDay1Binding
import android.widget.SeekBar
import android.os.SystemClock
import android.widget.TextView
import androidx.annotation.Dimension
// 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.
* Use the [day_1.newInstance] factory method to
* create an instance of this fragment.
*/
class day_1 : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var _binding: FragmentDay1Binding? = null
private val binding get() = _binding!!
private var mediaPlayer: MediaPlayer? = null
private val textsize_plus: Float = 10.0f
private lateinit var runnable: Runnable
private lateinit var handler: Handler
private lateinit var duration: TextView
private val j:Int = 0
var size:Float = 70.0f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
if(mediaPlayer?.isPlaying == true) {
//seekbar()
binding.textView2.text = "tankyou"
binding.seekBar.setProgress(mediaPlayer!!.currentPosition)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentDay1Binding.inflate(inflater,container,false)
if (mediaPlayer?.isPlaying == true) {
binding.seekBar.progress = mediaPlayer!!.currentPosition
}
binding.button1.setOnClickListener {
size -= textsize_plus
binding.gangu.setTextSize(Dimension.DP,size)}
binding.buttonplus.setOnClickListener {
size += textsize_plus
binding.gangu.setTextSize(Dimension.DP,size)}
//seekbar()
binding.startbutton.setOnClickListener {
if(mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(activity, R.raw.days_1)
binding.seekBar.max = mediaPlayer!!.duration
binding.seekBar.setProgress(mediaPlayer!!.currentPosition)
// seekbar()
}
mediaPlayer?.start()
}
binding.pausebutton.setOnClickListener {
if (mediaPlayer?.isPlaying == true) {
mediaPlayer?.pause()
binding.seekBar.setProgress(mediaPlayer!!.currentPosition)
} else {
mediaPlayer?.start()
}
}
binding.stopbutton.setOnClickListener {
mediaPlayer?.stop()
mediaPlayer=null
}
fun onStop() {
super.onStop()
mediaPlayer?.release()
}
binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if (b) {
mediaPlayer?.seekTo(i/* * 1000*/)
// seekbar()
if (mediaPlayer?.isPlaying == true) {
binding.seekBar.setProgress(mediaPlayer!!.currentPosition)
}
}
binding.textView4.text = "ok"
if (mediaPlayer?.isPlaying == true) {
binding.seekBar.setProgress(mediaPlayer!!.currentPosition)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
}
)
return binding.root
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment day_1.
*/
// TODO: Rename and change types and number of parameters
#JvmStatic
fun newInstance(param1: String, param2: String) =
day_1().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
override fun onPause() {
super.onPause()
mediaPlayer?.stop()
}
fun seekbar() {
binding.seekBar.setProgress(mediaPlayer!!.currentPosition)
val min2: Int = mediaPlayer!!.duration / 60000
val sec2: Int = (mediaPlayer!!.duration - min2 * 60000) / 1000
val min: Int = mediaPlayer!!.currentPosition / 60000
val sec: Int = (mediaPlayer!!.currentPosition - min * 60000) / 1000
binding.textView2.text = "" + min + " : " + sec + ""
binding.textView4.text = "" + min2 + " : " + sec2 + ""
runnable = Runnable { seekbar() }
handler.postDelayed(runnable, 1000)
}
}
I want to update seekBar by seconds. but No matter where I put setProgress code, it isn't working. SetProgress is just working on ButtonClick in this code. I want to make seekbar update by seconds. so I make seekbar function. but it isn't work. If I put seekbar function any places, application would be broken. So I cannot resolve this problem. Please help me...

Related

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException

I am facing such an error in my application. I guess the problem is due to having char in note_title and note_desc. I couldn't find the solution. Is there anyone who can help?
navgraph
error
NoteDetailScreen
notes entity
? and other char cause error
I tried change note_title and note_desc types but didnt work.
I solved this way;
Let’s say you have a class like this:
#Parcalize
#Entity(tableName = "NOTES")
data class Notes(
#PrimaryKey(autoGenerate = true)
#ColumnInfo("note_id") #NotNull var note_id:Int,
#ColumnInfo("note_title") #NotNull var note_title: String,
#ColumnInfo("note_desc") #NotNull var note_desc: String,
#ColumnInfo("note_date") #Nullable var note_date: String?
): Parcelable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString().toString(),
parcel.readString().toString(),
parcel.readString()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(note_id)
parcel.writeString(note_title)
parcel.writeString(note_desc)
parcel.writeString(note_date)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Notes> {
override fun createFromParcel(parcel: Parcel): Notes {
return Notes(parcel)
}
override fun newArray(size: Int): Array<Notes?> {
return arrayOfNulls(size)
}
}
}
annotation class Parcalize
You can define the NavType like this:
class NavTypo : NavType<Notes>(isNullableAllowed = false) {
override fun get(bundle: Bundle, key: String): Notes? {
return bundle.getParcelable(key)
}
override fun parseValue(value: String): Notes {
return Gson().fromJson(value, Notes::class.java)
}
override fun put(bundle: Bundle, key: String, value: Notes) {
bundle.putParcelable(key, value)
}
}
And use it:
composable(
"note_details_page/{note_id}",
arguments = listOf(
navArgument("note_id"){
type = NavTypo()
}
)
){
val note = it.arguments?.getParcelable<Notes>("note_id")
if (note != null) {
NoteDetailScreen(note, navController)
}
}
Card(
backgroundColor = choosedColor,
modifier = Modifier
.padding(3.dp)
.sizeIn(maxHeight = 250.dp)
.combinedClickable(onClick={
val note = allNotes.value!![it]
val noteJson = Uri.encode(Gson().toJson(note))
navController.navigate("note_details_page/${noteJson}")
}

Trying to fetch data from a JSON file and pass the data into fragment, but get an error

I am new to Kotlin and Android Studio and I am tasked with creating a tab layout with 3 tabs and with view pager and fragments. Each fragment will have a list of songs from different genres: Rock, Pop, and Classic. I am given APIs and I created json files from these APIs. I created the Xmls and setup the layouts, adapters, data classes, and everything. Now I'm trying to get the data from the json file into the fragment using recycler view and card view. Here is the error I am getting:
Type mismatch: inferred type is MainActivity but List was expected and Classifier 'MyAdapter' does not have a companion object, and thus must be initialized here. Here is my code:
//Main Activity
package com.example.itunes_mysia
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset
var artist_name: ArrayList<String> = ArrayList()
var track_name: ArrayList<String> = ArrayList()
var track_price: ArrayList<String> = ArrayList()
class MainActivity : AppCompatActivity() {
private lateinit var itunesToolbar: androidx.appcompat.widget.Toolbar
private lateinit var itunesTabs: TabLayout
private lateinit var itunesTitleText: TextView
private lateinit var itunesViewPager: ViewPager
private lateinit var itunesPagerAdapters: PagerAdapters
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
val linearLayoutManager = LinearLayoutManager(applicationContext)
recyclerView.layoutManager = linearLayoutManager
try {
val obj = JSONObject(loadJSONFromAsset())
val rockArray = obj.getJSONArray("Rock")
for (i in 0 until rockArray.length()) {
val userDetail = rockArray.getJSONObject(i)
artist_name.add(userDetail.getString("Artist"))
track_name.add(userDetail.getString("Track Name"))
track_price.add(userDetail.getString("Track Price"))
}
}
catch (e: JSONException) {
e.printStackTrace()
}
val myAdapter = MyAdapter(this#MainActivity)
recyclerView.adapter = MyAdapter
// Set find ID
itunesToolbar = findViewById(R.id.itunesToolbar)
itunesTitleText = findViewById(R.id.itunesTitleText)
itunesTabs = findViewById(R.id.itunesTabs)
itunesViewPager = findViewById(R.id.itunesViewPager)
itunesPagerAdapters = PagerAdapters(supportFragmentManager)
// Set Toolbar
itunesToolbar.setTitle("")
itunesTitleText.setText(getString(R.string.itunes))
setSupportActionBar(findViewById(R.id.itunesToolbar))
// Set Fragment List
itunesPagerAdapters.addfragment(RockFragment(), "Rock")
itunesPagerAdapters.addfragment(ClassicFFragment(), "Classic")
itunesPagerAdapters.addfragment(PopFragment(), "Pop")
// Set View Pager Adapter
itunesViewPager.adapter = itunesPagerAdapters
// Set Tab Layout with View Pager Adapter
itunesTabs.setupWithViewPager(itunesViewPager)
// Set Icons
itunesTabs.getTabAt(0)!!.setIcon(R.mipmap.music1)
itunesTabs.getTabAt(1)!!.setIcon(R.mipmap.music2)
itunesTabs.getTabAt(2)!!.setIcon(R.mipmap.music3)
}
class ViewPagerOnTabSelectedListener(private val viewPager: ViewPager) :
OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
// No-op
}
override fun onTabReselected(tab: TabLayout.Tab?) {
// No-op
}
}
private fun loadJSONFromAsset(): String {
val json: String?
try {
val inputStream = assets.open("rock.json")
val size = inputStream.available()
val buffer = ByteArray(size)
val charset: Charset = Charsets.UTF_8
inputStream.read(buffer)
inputStream.close()
json = String(buffer, charset)
}
catch (ex: IOException) {
ex.printStackTrace()
return ""
}
return json
}
}
//MyAdapter.kt (for recycler view)
package com.example.itunes_mysia
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MyAdapter(private val Rock: List<Rock>) :
RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
MyViewHolder {
val itemView= LayoutInflater.from(parent.context).inflate(R.layout.row, parent,
false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = Rock[position]
holder.artistName.text = currentItem.artistName
holder.trackName.text = currentItem.trackName
holder.trackPrice.text = currentItem.trackPrice
}
override fun getItemCount(): Int {
return Rock.size
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val artistName: TextView = itemView.findViewById(R.id.art_name)
val trackName: TextView = itemView.findViewById(R.id.trackName)
val trackPrice: TextView = itemView.findViewById(R.id.trackPrice)
}
}

Make a class have function with 3 parameter (int,string,double ) with return value int in Kotlin

fun main() {
val thr = THR()
thr.kotlin()
thr.hitungthr(5000000, "1", 1.5)
}
class THR {
fun kotlin() {
println("Perhitungan THR")
}
fun hitungthr (gajipokok: Int, masakerja: String, jumlahthr: Double): Int {
var MasaKerja = masakerja.toInt()
var JumlahTHR = jumlahthr.toInt()
var hasil = gajipokok * MasaKerja * JumlahTHR
return hasil
}
}
when the program is run, only the display "Perhitungan THR" appears. The second function does not appear when the program is run.
You need to print the value returned by the function hitungthr
fun main() {
val thr = THR()
thr.kotlin()
print(thr.hitungthr(5000000, "1", 1.5))
}
Try to add print() in your main() function and try it.

Asynchronous call in Kotlin not working with RecycleView

I'm struggling with asynchronous calls - the app is just crashing. I want to load a JSON-file (containing 100 JSON-objects) from an URL and then send it to RecyclerView.
Here is the MainActivity-class:
class MainActivity : AppCompatActivity() {
lateinit var recyclerView: RecyclerView
lateinit var linearLayoutManager: LinearLayoutManager
private val url = [//some address here]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = linearLayoutManager
AsyncTaskHandler().execute(url)
}
inner class AsyncTaskHandler : AsyncTask<String, String, String>() {
override fun onPreExecute() {
super.onPreExecute()
}
override fun doInBackground(vararg url: String?): String {
val text: String
val connection = URL(url[0]).openConnection() as HttpURLConnection
try {
connection.connect()
text = connection.inputStream.use { it.reader().use {reader -> reader.readText()} }
} finally {
connection.disconnect()
}
return text
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
}
}
private fun handleJson(jsonString: String?) {
val jsonArray = JSONArray(jsonString)
var list = mutableListOf<DataSet>()
var i = 0
while (i < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
list.add(DataSet(
jsonObject.getString("title"),
jsonObject.getString("type")
))
i++
}
val adapter = Adapter(list)
recyclerView.adapter = adapter
}
}
...and ListAdapter-class:
class Adapter (private var targetData: MutableList<DataSet>): RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.element, parent, false)
return ViewHolder(v);
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = targetData[position]
holder.title?.text = item.title
holder.type?.text = item.type
}
override fun getItemCount(): Int {
return targetData.size
}
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var title = itemView.findViewById<TextView>(R.id.itemTitle)
var type = itemView.findViewById<TextView>(R.id.itemType)
}
What might be the problem here? Is there any better option to perform this?

Keep tags order using SnakeYAML

I'm trying to translate yaml files to json, but the translation re-orders the tags...
Ex, YAML source:
zzzz:
b: 456
a: dfff
aa:
s10: "dddz"
s3: eeee
bbb:
- b1
- a2
snakeYAML produces:
{
"aa": {
"s3": "eeee",
"s10":"dddz"
},
"bbb":[
"b1",
"a2"
],
"zzzz": {
"a": "dfff",
"b":456
}
}
Create following class in your code, this is a tweaked version from the SnakeYAML source that uses LinkedHashMap and LinkedHashSet that keep the insertion order instead of TreeMap and TreeSet which auto-sort them.
import java.beans.FeatureDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.*;
import org.yaml.snakeyaml.util.PlatformFeatureDetector;
public class CustomPropertyUtils extends PropertyUtils {
private final Map<Class<?>, Map<String, Property>> propertiesCache = new HashMap<Class<?>, Map<String, Property>>();
private final Map<Class<?>, Set<Property>> readableProperties = new HashMap<Class<?>, Set<Property>>();
private BeanAccess beanAccess = BeanAccess.DEFAULT;
private boolean allowReadOnlyProperties = false;
private boolean skipMissingProperties = false;
private PlatformFeatureDetector platformFeatureDetector;
public CustomPropertyUtils() {
this(new PlatformFeatureDetector());
}
CustomPropertyUtils(PlatformFeatureDetector platformFeatureDetector) {
this.platformFeatureDetector = platformFeatureDetector;
/*
* Android lacks much of java.beans (including the Introspector class, used here), because java.beans classes tend to rely on java.awt, which isn't
* supported in the Android SDK. That means we have to fall back on FIELD access only when SnakeYAML is running on the Android Runtime.
*/
if (platformFeatureDetector.isRunningOnAndroid()) {
beanAccess = BeanAccess.FIELD;
}
}
protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) {
if (propertiesCache.containsKey(type)) {
return propertiesCache.get(type);
}
Map<String, Property> properties = new LinkedHashMap<String, Property>();
boolean inaccessableFieldsExist = false;
switch (bAccess) {
case FIELD:
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
for (Field field : c.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)
&& !properties.containsKey(field.getName())) {
properties.put(field.getName(), new FieldProperty(field));
}
}
}
break;
default:
// add JavaBean properties
try {
for (PropertyDescriptor property : Introspector.getBeanInfo(type)
.getPropertyDescriptors()) {
Method readMethod = property.getReadMethod();
if ((readMethod == null || !readMethod.getName().equals("getClass"))
&& !isTransient(property)) {
properties.put(property.getName(), new MethodProperty(property));
}
}
} catch (IntrospectionException e) {
throw new YAMLException(e);
}
// add public fields
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
for (Field field : c.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
if (Modifier.isPublic(modifiers)) {
properties.put(field.getName(), new FieldProperty(field));
} else {
inaccessableFieldsExist = true;
}
}
}
}
break;
}
if (properties.isEmpty() && inaccessableFieldsExist) {
throw new YAMLException("No JavaBean properties found in " + type.getName());
}
System.out.println(properties);
propertiesCache.put(type, properties);
return properties;
}
private static final String TRANSIENT = "transient";
private boolean isTransient(FeatureDescriptor fd) {
return Boolean.TRUE.equals(fd.getValue(TRANSIENT));
}
public Set<Property> getProperties(Class<? extends Object> type) {
return getProperties(type, beanAccess);
}
public Set<Property> getProperties(Class<? extends Object> type, BeanAccess bAccess) {
if (readableProperties.containsKey(type)) {
return readableProperties.get(type);
}
Set<Property> properties = createPropertySet(type, bAccess);
readableProperties.put(type, properties);
return properties;
}
protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) {
Set<Property> properties = new LinkedHashSet<>();
Collection<Property> props = getPropertiesMap(type, bAccess).values();
for (Property property : props) {
if (property.isReadable() && (allowReadOnlyProperties || property.isWritable())) {
properties.add(property);
}
}
return properties;
}
public Property getProperty(Class<? extends Object> type, String name) {
return getProperty(type, name, beanAccess);
}
public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) {
Map<String, Property> properties = getPropertiesMap(type, bAccess);
Property property = properties.get(name);
if (property == null && skipMissingProperties) {
property = new MissingProperty(name);
}
if (property == null) {
throw new YAMLException(
"Unable to find property '" + name + "' on class: " + type.getName());
}
return property;
}
public void setBeanAccess(BeanAccess beanAccess) {
if (platformFeatureDetector.isRunningOnAndroid() && beanAccess != BeanAccess.FIELD) {
throw new IllegalArgumentException(
"JVM is Android - only BeanAccess.FIELD is available");
}
if (this.beanAccess != beanAccess) {
this.beanAccess = beanAccess;
propertiesCache.clear();
readableProperties.clear();
}
}
public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) {
if (this.allowReadOnlyProperties != allowReadOnlyProperties) {
this.allowReadOnlyProperties = allowReadOnlyProperties;
readableProperties.clear();
}
}
public boolean isAllowReadOnlyProperties() {
return allowReadOnlyProperties;
}
/**
* Skip properties that are missing during deserialization of YAML to a Java
* object. The default is false.
*
* #param skipMissingProperties
* true if missing properties should be skipped, false otherwise.
*/
public void setSkipMissingProperties(boolean skipMissingProperties) {
if (this.skipMissingProperties != skipMissingProperties) {
this.skipMissingProperties = skipMissingProperties;
readableProperties.clear();
}
}
public boolean isSkipMissingProperties() {
return skipMissingProperties;
}
}
Then, create your Yaml instance like this:
DumperOptions options = new DumperOptions();
CustomPropertyUtils customPropertyUtils = new CustomPropertyUtils();
Representer customRepresenter = new Representer();
customRepresenter.setPropertyUtils(customPropertyUtils);
Yaml yaml = new Yaml(customRepresenter, options);
Profit!
The keeping of property order depends on java implementation and is not guaranteed.
In order to control the yaml generation you will need to implement your CustomRepresenter overriding the getProperties , see the example below:
package io.github.rockitconsulting.test.rockitizer.configuration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.representer.Representer;
/**
* Custom implementation of {#link Representer} and {#link Comparator}
* to keep the needed order of javabean properties of model classes,
* thus generating the understandable yaml
*
*/
public class ConfigurationModelRepresenter extends Representer {
public ConfigurationModelRepresenter() {
super();
}
public ConfigurationModelRepresenter(DumperOptions options) {
super(options);
}
protected Set<Property> getProperties(Class<? extends Object> type) {
Set<Property> propertySet;
if (typeDefinitions.containsKey(type)) {
propertySet = typeDefinitions.get(type).getProperties();
}
propertySet = getPropertyUtils().getProperties(type);
List<Property> propsList = new ArrayList<>(propertySet);
Collections.sort(propsList, new BeanPropertyComparator());
return new LinkedHashSet<>(propsList);
}
class BeanPropertyComparator implements Comparator<Property> {
public int compare(Property p1, Property p2) {
if (p1.getType().getCanonicalName().contains("util") && !p2.getType().getCanonicalName().contains("util")) {
return 1;
} else if(p2.getName().endsWith("Name")|| p2.getName().equalsIgnoreCase("name")) {
return 1;
} else {
return -1;
} // returning 0 would merge keys
}
}
}
The below snippet shows the usage of the newly created class to generate the yaml structure:
DumperOptions options = new DumperOptions();
ConfigurationModelRepresenter customRepresenter = new ConfigurationModelRepresenter();
Yaml yaml = new Yaml(customRepresenter, options);
StringWriter writer = new StringWriter();
yaml.dump(suite, writer);
FileWriter fw = new FileWriter(rootPathTestSrc + "config_gen.yml", false);
fw.write(writer.toString());
fw.close();
This approach is much cleaner, comparing to the one suggested above.