Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从异步HTTP post在viewpager上执行recyclerview_Android_Android Studio_Kotlin_Android Recyclerview_Android Viewpager - Fatal编程技术网

Android 如何从异步HTTP post在viewpager上执行recyclerview

Android 如何从异步HTTP post在viewpager上执行recyclerview,android,android-studio,kotlin,android-recyclerview,android-viewpager,Android,Android Studio,Kotlin,Android Recyclerview,Android Viewpager,目前,在Kotlin中设计一个应用程序时,实际上需要有两个不同的区域,可以在使用数据库结果的区域之间切换 所以现在我使用一个连接到2个片段的viewpager,fragment1工作得很好,因为我可以从mainactivity中填充它,因为它只使用一些文本视图 但是,片段2由一个具有可变项数的recyclerview填充 这两个都来自一个发送到我们网站的异步HTTP帖子,以“45,1,5,7”格式正确地显示为字符串,例如,我正在将其转换为Kotlin中的ArrayList 问题似乎是在切换到该数

目前,在Kotlin中设计一个应用程序时,实际上需要有两个不同的区域,可以在使用数据库结果的区域之间切换

所以现在我使用一个连接到2个片段的viewpager,fragment1工作得很好,因为我可以从mainactivity中填充它,因为它只使用一些文本视图

但是,片段2由一个具有可变项数的recyclerview填充

这两个都来自一个发送到我们网站的异步HTTP帖子,以“45,1,5,7”格式正确地显示为字符串,例如,我正在将其转换为Kotlin中的ArrayList

问题似乎是在切换到该数组之前,将其设置为片段2

在过去的几天里,我一直在尝试不同的解决方案,但我真的无法从这些方案中得到任何一个

我还尝试将适配器调用放在异步函数本身中,但这样做时它不会显示任何片段

到目前为止,唯一能产生正确结果的是在fragment2本身中放置第二个post请求,然而这只在刷过它之后才起作用,并且也没有立即执行,因此对于我所追求的东西来说,这并不真正可行

代码中不仅仅包含这些内容,所以只显示相关部分

创建时的主要活动(大量剥离):

@覆盖
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
window.decorView.systemui可见性=系统\用户界面\标志\全屏显示
actionBar?.hide()
setContentView(R.layout.activity_main)
grabtraps()//在执行异步函数时有效
val适配器=MyViewPagerAdapter(supportFragmentManager)
adapter.addFragment(fragment_1(),“一”)
addFragment(Fragment2(),“两个”)
//addFragment(FragmentThree(),“Three”)
//addFragment(FragmentFour(),“Four”)
vpPager.adapter=适配器
val tabs2=findViewById(R.id.tabs);
选项卡2.设置WithViewPager(vpPager)
//正如我前面所说,在函数中尝试了这个功能,但总体上没有出现。
}
Grabtraps()-仍在MainActivity中-自从fragment1工作以来,我已经剥离了很多和它相关的东西


    fun grabtraps(){


        val sharedPref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)

        val username = sharedPref.getString("user", "Not logged in")

        val jsoncode = JSONObject()
        jsoncode.put("username", username)

// Basically getting username into the HTTPS Post, PHP pics it up on the otherside

        "https://fakesite.com/gettraps.php".httpPost()
                .header("Content-Type", "application/json")
                .body(jsoncode.toString())
                .response{
                    request, response, result ->
                    when (result) {

                        is Result.Failure -> {

// Can probably skip this side - occurs if fails to connect.

                            mResultTextView = findViewById(R.id.result_textview)



                            var inputto = sharedPref.getString("user", "Please Log in")
                            if(inputto != "Please Log in"){
                                inputto = "Welcome, $inputto"
                            }
                            mResultTextView.text = inputto


                        }
                        is Result.Success -> {

                            val output = String(response.data)

                            val delimiter = ","

                            val parts = output.split(delimiter)

// Effectivelly just the output then put into an ArrayList<String>


                            var myDataset = ArrayList<String>()
                            myDataset.add("1")
                            myDataset.add("2")
                            myDataset.add("3")
// Decided to just test with dummydata for now till I can see it

                            val test = Fragment2.MyAdapter(myDataset)

//Accidently didn't remove this part, but was trying this along with some other code I got rid of to test fragment2, didn't work though.


                            val sitespref: SharedPreferences = getSharedPreferences(LAST_SITES, PRIVATE_MODE)


                            val editor3 = sitespref.edit()

                            editor3.clear()
                            editor3.putString("sites",output)
                            editor3.apply()

//Tried using getsharedpreferences, saving the content then loading it on the otherside, as expected though it just loads up from the last time I did this so results are outdated.


                            mResultTextView = findViewById(R.id.result_textview)



                            findViewById<TextView>(R.id.catchsitevariable).text = parts[0]

// Was just a test to see if I could override it the same way as the others - catchsitevariable is a textview in my recyclerview on the viewpager fragment






                        }
                    }
                }

    }



有趣的陷阱(){
val sharedPref:SharedPreferences=getSharedPreferences(首选名称,私有模式)
val username=sharedPref.getString(“用户”,“未登录”)
val jsoncode=JSONObject()
jsoncode.put(“用户名”,用户名)
//基本上,把用户名放到HTTPS帖子中,PHP会在另一端将其拍照
"https://fakesite.com/gettraps.php“.httpPost()
.header(“内容类型”、“应用程序/json”)
.body(jsoncode.toString())
.答复{
请求、响应、结果->
何时(结果){
是结果。失败->{
//可能会跳过此端-如果连接失败则会发生。
mResultTextView=findviewbyd(R.id.result\u textview)
var inputto=sharedPref.getString(“用户”,“请登录”)
如果(输入!=“请登录”){
inputto=“欢迎,$inputto”
}
mResultTextView.text=inputto
}
这就是结果。成功->{
val输出=字符串(response.data)
val分隔符=“,”
val parts=output.split(分隔符)
//有效地只是将输出放入ArrayList
var myDataset=ArrayList()
myDataset.add(“1”)
myDataset.add(“2”)
myDataset.add(“3”)
//决定现在就用dummydata进行测试,直到我能看到它为止
val test=Fragment2.MyAdapter(myDataset)
//无意中没有删除此部分,但尝试将其与其他代码一起使用以测试fragment2时,结果无效。
val sitespref:SharedReferences=GetSharedReferences(最后一个站点,私有模式)
val editor3=sitespref.edit()
editor3.clear()
editor3.putString(“站点”,输出)
editor3.apply()
//尝试使用GetSharedReferences,保存内容,然后在另一端加载,正如预期的那样,虽然它只是从上次我这样做时加载的,所以结果已经过时。
mResultTextView=findviewbyd(R.id.result\u textview)
findViewById(R.id.catchsitevariable)。text=parts[0]
//这只是一个测试,看看我是否可以像其他人一样覆盖它-catchsitevariable是viewpager片段上我的recyclerview中的textview
}
}
}
}
MyViewPagerAdapter-仍在MainActivity上,工作正常,但我想我会把它包括进来以防万一,因为它是相关的


    class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){

        private val fragmentList : MutableList<Fragment> = ArrayList()
        private val titleList : MutableList<String> = ArrayList()

        override fun getItem(position: Int): Fragment {
            return fragmentList[position]
        }

        override fun getCount(): Int {
            return fragmentList.size
        }

        fun addFragment(fragment: Fragment,title:String){
            fragmentList.add(fragment)
            titleList.add(title)
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return titleList[position]
        }

    }





类MyViewPagerAdapter(管理器:FragmentManager):FragmentPagerAdapter(管理器){
private val fragmentList:MutableList=ArrayList()
private val titleList:MutableList=ArrayList()
覆盖趣味getItem(位置:Int):片段{
返回碎片列表[位置]
}
重写fun getCount():Int{
返回fragmentList.size
}
FunAddFragment(片段:片段,标题:字符串){
碎片列表。添加(碎片)
标题列表。添加(标题)
}
覆盖有趣的getPageTitle(位置:Int):字符序列{
返回标题列表[位置]
}
}

    class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){

        private val fragmentList : MutableList<Fragment> = ArrayList()
        private val titleList : MutableList<String> = ArrayList()

        override fun getItem(position: Int): Fragment {
            return fragmentList[position]
        }

        override fun getCount(): Int {
            return fragmentList.size
        }

        fun addFragment(fragment: Fragment,title:String){
            fragmentList.add(fragment)
            titleList.add(title)
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return titleList[position]
        }

    }







    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        val name = arguments?.getString(ARG_NAME)


               return inflater.inflate(R.layout.page2fragment, container, false)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        var recyclerView: RecyclerView = view.findViewById<RecyclerView>(R.id.recyclesites)

var myDataset = ArrayList<String>()


        val sharedPref: SharedPreferences = this.activity!!.getSharedPreferences(PREF_NAME, PRIVATE_MODE)

        val username = sharedPref.getString("user", "Not logged in")

        val sites: SharedPreferences = this.activity!!.getSharedPreferences(LAST_SITES, PRIVATE_MODE)

        val output = sites.getString("sites","")

        println("output is $output")

// Was using this to test saving it, if nothing saved just comes out "output is" otherwise comes out with the previous result, this is getting called before the Async request in MainActivity is done.

        val delimiter = ","

        val parts = output.split(delimiter)

        viewManager = LinearLayoutManager(getActivity())
        viewAdapter = MyAdapter(myDataset)

        recyclerView = view.findViewById<RecyclerView>(R.id.recyclesites).apply {
            setHasFixedSize(true)

            layoutManager = viewManager

            val adapter = MyAdapter(myDataset)
            adapter.replaceItems(myDataset)
            adapter.getItemCount()
            adapter.testing(findViewById<RecyclerView>(R.id.recyclesites))
            recyclerView.adapter = adapter


        }

    }



    class MyAdapter(private val myDataset: ArrayList<String>) :
            RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

        private var items = ArrayList<String>()

        class MyViewHolder(val textView: RelativeLayout) : RecyclerView.ViewHolder(textView)


        override fun onCreateViewHolder(parent: ViewGroup,
                                        viewType: Int): MyAdapter.MyViewHolder {

            val textView = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recyclesites, parent, false) as RelativeLayout
            return MyViewHolder(textView)
        }
        fun replaceItems(items: ArrayList<String>) {
            this.items = items
            notifyDataSetChanged()
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.textView.text = myDataset[position]
        }

        fun testing(parent: ViewGroup): MyAdapter.MyViewHolder{
            val textView = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recyclesites, parent, false) as RelativeLayout
            return MyViewHolder(textView)

//Effectivelly what I used to inflate the actual inner parts of the recyclerview

        }
        // Return the size of your dataset (invoked by the layout manager)
        override fun getItemCount(): Int{
            println(myDataset.size)
// Was coming out 0 for most attempts when trying to send the data across.

            return myDataset.size
        }
    }