0

Background:

  • I am trying to display bar chart based on the Fragments clicked, I have two fragments and one activity in my test project.
  • I am using MPAndroidBarchart and kotlin is used for this test project.
  • Library used is com.github.mikephil.charting.charts.BarChart.

I have issues below:

  • I am getting following error message:

    barChart must not be null

    I checked the Log message and I am getting the JSON value before that message. Error is started from this piece of code barChart.data = data

  • Default fragment one is not invoked by default, but if I click the second Fragment and then I click the first fragment, then Fragment 1 is invoked. Otherwise it's not working or throwing the above error.

Attached the code:

JSON Response

[{"day":"2018-12-12","value":"1"},{"day":"2018-12-13","value":"2"},{"day":"2018-12-14","value":"3"},{"day":"2018-12-15","value":"4"},{"day":"2018-12-17","value":"5"},{"day":"2018-12-18","value":"6"},{"day":"2018-12-19","value":"7"}]

Fragment:1

class FirstFragment : Fragment() {

    var volleyRequest: RequestQueue?=null
    val TestLink="https://wwww.abc.app"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        volleyRequest= Volley.newRequestQueue(this.context)
        getTestValue(TestLink)
    }


    fun getTestValue(Url:String)
    {
        val stringReq=StringRequest(Request.Method.GET,Url,
                Listener {
                    response: String? ->
                    try {
        Log.d("Response JSON",response.toString())
                        ///Bar Chart Test
                        val jsonStringArray=response.toString()
                        println("Attempt to fetch JSON Data")
                        val entries = ArrayList<BarEntry>()
                        val labels = ArrayList<String>()
                        val arr = JSONArray(jsonStringArray)
                        for (i in 0 until arr.length()) {
                            entries.add(BarEntry(arr.getJSONObject(i).getDouble("value").toFloat(), i))
                            labels.add(arr.getJSONObject(i).getString("day"))
                        }
                        val barDataSet = BarDataSet(entries, "Test Sample Record")
                        barDataSet.valueTextSize = 10f
                        val data = BarData(labels, barDataSet)
                        Log.d("Entries", data.toString())
                        barChart.data = data 
                        barChart.setDescription("")
                        }
                    catch (e:JSONException)
                    {
                        e.printStackTrace()
                    }

                },
                Response.ErrorListener {
                    error: VolleyError? ->
                    try{
                        Log.d("Error:", error.toString())
                    }
                    catch (e:JSONException) {e.printStackTrace()}
                }
                )
        volleyRequest!!.add(stringReq)
    }
}

Main Activity:

class MainActivity : AppCompatActivity() {

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
               // message.setText(R.string.title_home)
                replaceFragment(FirstFragment())
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                //message.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                //message.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

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

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }

    private fun replaceFragment(fragment: Fragment){
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.container, fragment)
        fragmentTransaction.commit()
    }
}

active_fragment_one

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

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/barChart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ColorBg"
        />

</FrameLayout>
Jo.........
  • 190
  • 1
  • 3
  • 13

1 Answers1

1

I don't know about your onCreateView() in FirstFragment but your issue is called a View when it not be created yet, so move your code in onCreate to

@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        volleyRequest= Volley.newRequestQueue(this.context)
        getTestValue(TestLink)
    }
GianhTran
  • 3,443
  • 2
  • 22
  • 42
  • Hi @Gianh Tran, Thanks for your explanation. I am new to Fragment so, can you explain me where I need to add the onViewcreated method in the code. – Jo......... Dec 20 '18 at 07:26
  • because in `onCreate`, we do not inflate layout here, so you can not use any view here. you should research about `fragment lifecycle` for more information – GianhTran Dec 20 '18 at 07:31
  • Woow. Your solution worked for me. Can you explain me the difference between onCreateView and onViewCreate methods. Thanks for your help. – Jo......... Dec 20 '18 at 07:40
  • @JoshvaJo nice to help, you can see more in https://stackoverflow.com/questions/25119090/difference-between-oncreateview-and-onviewcreated-in-fragment – GianhTran Dec 20 '18 at 07:47
  • Tran. Thanks for the link. – Jo......... Dec 20 '18 at 08:44