RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-0

's questions

Martin Hope
user501848
Asked: 2024-11-01 05:54:11 +0000 UTC

为什么在使用curl 的函数内调用unlink() 后cookie 文件仍然存在?

  • 4
<?
  function request($url, $method = 'GET', $fields = null, $cookiesPath = null, $keepCookies = true) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if (strtoupper($method) === 'GET' && $fields) {
      $url .= '?' . http_build_query($fields);
      curl_setopt($ch, CURLOPT_URL, $url);
    } else if (strtoupper($method) === 'POST') {
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen(json_encode($fields))
      ]);
    }

    if (!$cookiesPath) {
      $cookiesRandomName = substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyz', ceil(30 / 36))), 0, 30);
      $cookiesPath = __DIR__ . $cookiesRandomName . '.txt';
    }

    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiesPath);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiesPath);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

    $response = curl_exec($ch);

    if ($errorCode = curl_errno($ch)) {
      $errorMessage = curl_error($ch);
        
      curl_close($ch);

      if (file_exists($cookiesPath)) {
        unlink($cookiesPath);
      }

      return [ 'error' => [ 'code' => $errorCode, 'message' => $errorMessage ] ];
    }

    $HTTP_CODE = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($keepCookies) {
      return [ 'HTTP_CODE' => $HTTP_CODE, 'response' => json_decode($response, true), 'cookiesPath' => $cookiesPath ];
    } else {
      if (file_exists($cookiesPath)) {
        unlink($cookiesPath); // Место ошибки
      }

      return [ 'HTTP_CODE' => $HTTP_CODE, 'response' => json_decode($response, true) ];
    }
  }

我正在编写一个 PHP 脚本,它使用 request() 函数发出 HTTP 请求。在此函数内,我尝试使用 unlink() 删除临时 cookie 文件,但尽管该函数返回成功删除消息,但该文件仍存在于磁盘上。使用示例:

$response = request('https://example.com/login', 'post', [ 'login' => 'name', 'password' => 'hash' ]);
$response = request('https://example.com/profile', 'get', null, $response['cookiesPath'], false);

令人惊讶的是,当 unlink() 在函数外部使用时,不会发生此类事件。一般来说,有趣的行为和最大的陌生感。使用适用于 Windows 11 的 XAMPP。还在 Apache/2.4.6 上的托管上进行了测试。

php
  • 1 个回答
  • 77 Views
Martin Hope
user605973
Asked: 2024-07-25 18:34:25 +0000 UTC

如何使用 M1 Pro 在 Mac 上为 Duolingo 和 Python 创建四个虚拟机?

  • 1

Python 中有一个 Duolingo 机器人,带有 pyautogui 和 numpy。我需要打开四个 Duolingos,但该应用程序不允许我打开多个窗口,而且我也不知道如何在 Mac 上添加三个以上的光标,以便通过 Python 异步控制它们(很可能是异步或线)。根据答案,我也理解了@ari的评论,有虚拟机的选项,我该怎么做?简而言之:如何在 Mac 上打开一个不允许您多次打开的应用程序(Python(您可以使用线程/异步)和 Duolingo)。

您需要的是应用程序。或者我是否应该以一种或另一种方式看待Python的错误方向,选择哪些工具以及如何做?

python
  • 1 个回答
  • 183 Views
Martin Hope
user561333
Asked: 2023-07-22 02:48:11 +0000 UTC

Linux命令以树形显示目录结构

  • 5

我可以从 Bash 脚本调用任何 Linux 命令,该命令会将目录结构打印为树状结构,如下所示:

dir1
  aa.txt
  bb.txt
dir2
  dir3
...
linux
  • 1 个回答
  • 112 Views
Martin Hope
user538760
Asked: 2023-01-30 16:44:12 +0000 UTC

如何使用过滤器映射排序按条件从对象数组中获取已排序的名称数组

  • 4

完成代码,使 names 变量包含按字母顺序排列的作者姓名数组,这些作者的图书评级大于MIN_BOOK_RATING变量的值。

const books = [
  {
    title: "The Last Kingdom",
    author: "Bernard Cornwell",
    rating: 8.38,
  },
  {
    title: "Beside Still Waters",
    author: "Robert Sheckley",
    rating: 8.51,
  },
  {
    title: "The Dream of a Ridiculous Man",
    author: "Fyodor Dostoevsky",
    rating: 7.75,
  },
  { title: "Redder Than Blood", author: "Tanith Lee", rating: 7.94 },
  {
    title: "The Dreams in the Witch House",
    author: "Howard Lovecraft",
    rating: 8.67,
  },
];
const MIN_BOOK_RATING = 8;
// Change code below this line

const names = books
  .filter((rating, index, array) => array.indexOf(rating) > MIN_BOOK_RATING)
  .map(rating => rating.author)
  .sort((a, b) => a.localeCompare(b));
  
console.log(names)

求助,我想不通。

javascript
  • 2 个回答
  • 38 Views
Martin Hope
user530179
Asked: 2022-11-29 04:39:40 +0000 UTC

用公式 2nx/(n+1) 组成 A = 的循环公式!

  • 5

由公式 An=2nx/(n+1) 构成 An+1 的循环公式!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp17
{
    internal class Program
    {
        static void Main(string[] args)
        {
            const double E = 0.001;
            double A, S;
            int n;
            Console.WriteLine("x=");
            double x = Convert.ToDouble(Console.ReadLine());
            S=0;
            n=0;
            A=x;
            do
            {
                S=S+A;
                n=n+1;
                A=A*x*(2*n+1)/((2*n-1)*(n+1)); //пример правильной рекурентной формулы для другой формулы ... x^n*(2n-1)/n!
            }
            while (A>=E);
            Console.WriteLine($"{S}, {n}");
            Console.ReadKey();
        }
    }
}
c#
  • 3 个回答
  • 51 Views
Martin Hope
user462422
Asked: 2022-09-17 14:54:48 +0000 UTC

如何修复 c++ 错误?

  • -1

我最近开始学习 c++,其中一项作业是: 在此处输入图像描述

我写了代码,但不是正常响应,而是开始输出:

-nan(ind)

我知道这意味着我在根下有一个负值,但我不明白如果一切都是平方的结果如何。告诉我出了什么问题以及如何修复代码?代码本身:

#include <iostream>

using namespace std;

template <typename T>

T Sigma_Array(const T* array, int count)
{
    T sum = 0;

    for (int i = 0; i < count; count++)
    {
        sum += array[i];
    }

    T average = sum / count;

    T square_s = 1. / count;

    for (int i = 0; i < count; count++)
    {
        T difference = array[i] - average;
        square_s *= pow(difference, 2);
    }

    return sqrt(square_s);
}


int main()
{
    float array_1[5] = {0.5, 1.5, 2.5, 3.5, 2.0};

    cout << Sigma_Array(array_1, 5);
    return 0;
}
c++
  • 0 个回答
  • 0 Views
Martin Hope
user518983
Asked: 2022-09-11 13:21:40 +0000 UTC

如何在css中制作剪切文本效果?

  • 0

我正在尝试制作剪切文本的效果,如图所示。通过混合混合模式尝试,它可以工作,但是当我放置白色背景时,字母也是白色的。有没有可能在图片中做类似的事情?毕竟,现在我通过 background-image 在背景和文本的背景上插入了一张图片

* {
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, Helvetica, sans-serif;
}

.test {
    background-image: url(https://kartinkin.net/uploads/posts/2021-07/thumbs/1625664173_41-kartinkin-com-p-oboi-s-tsvetami-krasivie-42.jpg);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    width: 100%;
    height: 100vh;
    position: relative;
}

.title {
    font-size: 100px;
    position: absolute;
    top: 50%;
    right: calc(50% - 250px);
    color: #fff;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-image: url(https://kartinkin.net/uploads/posts/2021-07/thumbs/1625664173_41-kartinkin-com-p-oboi-s-tsvetami-krasivie-42.jpg);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    clip-path: polygon(49.2% 0, 100% 0%, 100% 100%, 50% 100%);
    background-color: #fff;
    pointer-events: none;
    z-index: 11;
}

.subtitle {
    content: 'FLOWERS';
    position: absolute;
    color: #fff;
    top: 50%;
    right: calc(50% - 250px);
    font-size: 100px;
    clip-path: polygon(0 0, 49.2% 0, 50% 100%, 0 100%);
    pointer-events: none;
}

.white {
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    width: 50.1%;
    background-color: #fff;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Test</title>
</head>

<body>
    <section class="test">
        <h1 class="title">FLOWERS</h1>
        <h1 class="subtitle">FLOWERS</h1>
        <div class="white"></div>
    </section>
</body>

</html>
在此处输入图像描述

html
  • 0 个回答
  • 0 Views
Martin Hope
user514769
Asked: 2022-09-10 02:45:05 +0000 UTC

无法将数字传递给片段

  • 1

片段运行:

val fragment = DescriptionFragment()
val bundle = Bundle()
bundle.putInt("position", position)
fragment.setArguments(bundle)

val activity=context.context as AppCompatActivity
activity.supportFragmentManager
    .beginTransaction()
    .replace(R.id.framelayout, fragment)
    .commitNow()

试图在正在运行的片段中获取传递的数字:

val position: Int = getArguments()?.getInt("position", 0) ?: 0

问题是它position总是等于默认值——即 0。

android
  • 0 个回答
  • 0 Views
Martin Hope
user514769
Asked: 2022-09-10 00:20:24 +0000 UTC

如何在从另一个片段的 RecyclerView 适配器启动的片段中实现回溯

  • 0

我需要能够在正在运行的片段中返回到上一个片段:

[![在此处输入图像描述][1]][1]

片段本身在 RecyclerView 适配器中启动(如果这很重要)

我尝试通过addToBackStack(null)在启动代码中添加一个片段来实现回溯:

    val activity=context.context as AppCompatActivity
    activity.supportFragmentManager
        .beginTransaction()
        .replace(R.id.framelayout, fragment).
        addToBackStack(null)
        .commit()

不幸的是,这不起作用(并且在使用时commitNow(),它会抛出一个错误)

目前,无论是通过按钮还是以类似于上面代码中给出的方式进行操作对我来说都无关紧要,主要是它可以工作

android
  • 0 个回答
  • 0 Views
Martin Hope
user515715
Asked: 2022-09-09 22:13:16 +0000 UTC

无法将本地数据库中的数据获取到文本字段中

  • 0

有一个片段DescriptionFragment:

class DescriptionFragment : Fragment() {

    private var binding : FragmentDescriptionBinding? = null
    private val descriptionViewModel : DescriptionViewModel by viewModel()

    val position: Int = getArguments()?.getInt("position", 0) ?: 0

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

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_description, container, false)

        binding?.name?.text = descriptionViewModel.loadDescription.value?.get(position)?.name
        Log.d("OnClick", "name во втором фрагменте " + descriptionViewModel.loadDescription.value?.get(position)?.name)
        binding?.date?.text = descriptionViewModel.loadDescription.value?.get(position)?.date
        binding?.description?.text = descriptionViewModel.loadDescription.value?.get(position)?.description

        return binding?.root
    }

}

它应该从数据库中获取数据Room到文本字段中。问题是它到达那里null。

Log "OnClick"写name во втором фрагменте null

但是 UseCase 仍然存在一些问题(如果我正确理解了日志中写的内容): Log "OnClick"写DescriptionUseCase androidx.room.RoomTrackingLiveData@20ac29a

DataSourceIMPL:

class DataSourceIMPL (private val dao: NameListDao):
    RDDataSource {

    override fun insert(paginationLocalModel: PaginationLocalModel) {
        CoroutineScope(Dispatchers.IO).launch {
            dao.insert(paginationLocalModel)}
    }

    override fun loadNameList(): LiveData<List<PaginationLocalModel>> {
        return dao.loadNameList()
    }

    override suspend fun clear() {
        CoroutineScope(Dispatchers.IO).launch {
            dao.clear()}
    }


}

NameListDao:

@Dao
interface NameListDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(paginationLocalModel: PaginationLocalModel)

    @Query("SELECT * FROM pagination_table")
    fun loadNameList() : LiveData<List<PaginationLocalModel>>

    @Query("DELETE FROM pagination_table")
    suspend fun clear()
}

DescriptionRepository:

class DescriptionRepository(private val dataSource: RDDataSource) : DescriptionCall {

    override fun loadDescription(): LiveData<List<PaginationLocalModel>> {
        return dataSource.loadNameList()
      
    }

}

DescriptionUseCase:

class DescriptionUseCase(private val descriptionCall: DescriptionCall) {

    fun loadDescription(): LiveData<List<PaginationLocalModel>> {

        Log.d("OnClick", "DescriptionUseCase " + descriptionCall.loadDescription())
        return descriptionCall.loadDescription()

    }

}

DescriptionViewModel:

class DescriptionViewModel(private val descriptionUseCase: DescriptionUseCase) : ViewModel() {

    val loadDescription = descriptionUseCase.loadDescription()

}

PaginationLocalModel:

@Entity(tableName = "pagination_table")
class PaginationLocalModel (

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "date")
    val date: String,

    @ColumnInfo(name = "description")
    val description: String

)
android
  • 0 个回答
  • 0 Views
Martin Hope
user472244
Asked: 2022-09-09 20:43:28 +0000 UTC

如何让动画在一定高度开启

  • 0

我在 JS 中有一个动画,它和其他所有东西一样,随着页面一起加载,你需要让它在某个高度打开。提前致谢!!

const counters = document.querySelectorAll(".num");

counters.forEach((counter) => {
    counter.innerHTML = "0";

    const updateCounter = () => {
        const target = +counter.getAttribute("data-target");
        const c = +counter.innerText;

        if (c < target) {
            counter.innerText = c + 1;
            setTimeout(updateCounter, 100);

        }
        else {
            counter.innerText = target;
        }
    };
    updateCounter()
});

动画本身

如果在纯 JS 中会很酷

javascript
  • 0 个回答
  • 0 Views
Martin Hope
user514769
Asked: 2022-09-09 14:50:27 +0000 UTC

尝试从 RecyclerVIew 适配器运行片段时发生错误

  • -1

错误文字:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sem.receivedata, PID: 21279
    java.lang.ClassCastException: com.sem.receivedata.databinding.FragmentNameListBindingImpl cannot be cast to com.sem.receivedata.databinding.FragmentDescriptionBinding
        at com.sem.receivedata.presentation.DescriptionFragment.onCreateView(DescriptionFragment.kt:28)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1758)
        at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1670)
        at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:317)
        at com.sem.receivedata.presentation.adapters.NameListAdapter$NameListHolder.bind$lambda-0(NameListAdapter.kt:58)

DescriptionFragment.kt:28指向一个字符串binding = DataBindingUtil.inflate(inflater, R.layout.fragment_name_list, container, false)

NameListAdapter.kt:58指着:

        activity.supportFragmentManager
            .beginTransaction()
            .replace(R.id.framelayout, fragment)
            .commitNow()

NameListHolder:

class NameListHolder(val binding: NameListItemBinding) : RecyclerView.ViewHolder(binding.root) {

    fun bind(paginationLocalModel: PaginationLocalModel, position: Int, context: NameListFragment){

        binding.name.text = paginationLocalModel.name
        itemView.setOnClickListener{

            val fragment = DescriptionFragment()
            val bundle = Bundle()
            bundle.putInt("position", position)
            fragment.setArguments(bundle)

            val activity=context.context as AppCompatActivity
            activity.supportFragmentManager
                .beginTransaction()
                .replace(R.id.framelayout, fragment)
                .commitNow()

            Log.d("OnClick", "произошло нажатие по позиции $position")
        }

    }

}

DescriptionFragment:

class DescriptionFragment : Fragment() {

    private var binding : FragmentDescriptionBinding? = null
    private val descriptionViewModel : DescriptionViewModel by viewModel()

    val position: Int = getArguments()?.getInt("position", 0) ?: 0

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

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_name_list, container, false)

        binding?.name?.text = descriptionViewModel.loadDescription.value?.get(position)?.name
        binding?.date?.text = descriptionViewModel.loadDescription.value?.get(position)?.date
        binding?.description?.text = descriptionViewModel.loadDescription.value?.get(position)?.description

        return binding?.root
    }

}

第一个片段(包含 RecyclerView)在标记内运行Activity:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".presentation.MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/framelayout"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <fragment
                android:id="@+id/rd_fragment"
                android:name="com.sem.receivedata.presentation.NameListFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </FrameLayout>

    </androidx.appcompat.widget.LinearLayoutCompat>

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>
android
  • 0 个回答
  • 0 Views
Martin Hope
user515715
Asked: 2022-09-08 13:44:25 +0000 UTC

从具有多层的 Json 中使用 Retrofit 获取数据

  • 0

有json:

{
  "success": true,
  "result": {
    "current_page": 1,
    "data": [
      {
        "id": 1,
        "name": "Hayley O'Keefe",
        "description": "Eveniet sed exercitationem distinctio voluptatum qui magnam ratione et soluta itaque explicabo laborum nemo mollitia et veniam aut sed voluptatibus at sequi aut consequatur labore quod vel iusto...",
        "date": "1991-03-24"
      },
      {
        "id": 2,
        "name": "Terry Schaefer",
        "description": "Consectetur explicabo porro quis debitis itaque corrupti eius beatae aliquid facilis ea quo soluta porro est facere ut quia sit provident suscipit ut eos inventore est aperiam nostrum sit reprehenderit...",
        "date": "1988-08-27"
      },
      {
        "id": 3,
        "name": "Jude Sporer DVM",
        "description": "Explicabo illum et excepturi doloremque quidem laboriosam excepturi quae fugit nostrum et enim enim libero vitae sit perspiciatis quis consequatur eum ratione sequi doloribus voluptatem velit commodi...",
        "date": "1984-02-14"
      },
      {
        "id": 4,
        "name": "Prof. Leola Rogahn",
        "description": "Quia iste id sint repellat debitis illo ex et commodi et repellendus consequuntur consequatur modi molestiae...",
        "date": "2005-10-29"
      },
      {
        "id": 5,
        "name": "Jaylon VonRueden",
        "description": "Aspernatur sit iusto enim asperiores est quis autem tempore fuga qui omnis inventore nostrum ab debitis ducimus voluptatem quia ipsa placeat molestiae dolores doloremque ipsa tempore vero...",
        "date": "2019-04-09"
      },
      {
        "id": 6,
        "name": "Margie Kertzmann",
        "description": "Aut itaque non expedita laborum vero inventore ipsa commodi nobis accusantium hic aspernatur ab fuga molestiae dignissimos eaque voluptatum sapiente totam et exercitationem dolorem qui tempora...",
        "date": "2020-12-10"
      },
      {
        "id": 7,
        "name": "Monserrat Kulas",
        "description": "Eum sunt eius ab sit qui soluta quisquam quam qui vel eaque exercitationem error necessitatibus aspernatur qui optio et qui doloribus necessitatibus aut et reprehenderit doloremque non et dolor...",
        "date": "1976-02-25"
      },
      {
        "id": 8,
        "name": "Dr. Filomena Pagac PhD",
        "description": "Dolores nostrum fugiat incidunt et sapiente sunt dolores et illo magnam repudiandae dolores et voluptas inventore error iusto rem ut aperiam quo similique eveniet ut culpa veniam recusandae pariatur delectus...",
        "date": "1984-02-05"
      },
      {
        "id": 9,
        "name": "Camden Armstrong",
        "description": "Est aspernatur tempore necessitatibus rerum aut placeat incidunt molestias molestiae voluptatem at non vitae...",
        "date": "1980-04-05"
      },
      {
        "id": 10,
        "name": "Jade Mosciski",
        "description": "Quis odio ut nihil non eum accusamus voluptatem minus deleniti non tempora eligendi ullam consequatur dignissimos ....",
        "date": "1978-04-05"
      }
    ],
    "first_page_url": "http://candidate.scid.ru/api/books?page=1",
    "from": 1,
    "last_page": 10,
    "last_page_url": "http://candidate.scid.ru/api/books?page=10",
    "links": [
      {
        "url": null,
        "label": "&laquo; Previous",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=1",
        "label": "1",
        "active": true
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=2",
        "label": "2",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=3",
        "label": "3",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=4",
        "label": "4",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=5",
        "label": "5",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=6",
        "label": "6",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=7",
        "label": "7",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=8",
        "label": "8",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=9",
        "label": "9",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=10",
        "label": "10",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=2",
        "label": "Next &raquo;",
        "active": false
      }
    ],
    "next_page_url": "http://candidate.scid.ru/api/books?page=2",
    "path": "http://candidate.scid.ru/api/books",
    "per_page": 10,
    "prev_page_url": null,
    "to": 10,
    "total": 100
  },
  "error": null
}

如果你把它分解成模型,你会得到以下层次结构(如果我没有混淆任何东西):

在此处输入图像描述

模型本身:

Pagination:

data class Pagination(
    val error: Any,
    val result: Result,
    val success: Boolean
)

Result:

data class Result(
    val current_page: Int,
    val `data`: List<Data>,
    val first_page_url: String,
    val from: Int,
    val last_page: Int,
    val last_page_url: String,
    val links: List<Link>,
    val next_page_url: String,
    val path: String,
    val per_page: Int,
    val prev_page_url: Any,
    val to: Int,
    val total: Int
)

Data:

data class Data(
    val date: String,
    val description: String,
    val id: Int,
    val name: String
)

Link:

data class Link(
    val active: Boolean,
    val label: String,
    val url: String
)

我需要从中获取数据Data

问题来了。由于我需要在层次结构中更高的模型中“包装”两次Data,因此我为此目的创建了以下类:

PaginationApiModel:

class PaginationApiModel {

    @SerializedName("result") @Expose
    val result: ResultApiModel? = null

}

ResultApiModel:

class ResultApiModel {

    @SerializedName("data") @Expose
    val data: ArrayList<Data>? = null

}

但是我需要从 Json 获取一组数据,这就是为什么我不太明白ApiDataSourceIMPL如果我将它替换为ArrayList<Data>如何实现这个类片段PaginationApiModel:

        for (audit in loadNameList) {

            audit.id?.let {
                PaginationLocalModel(
                    it,

                    audit.name.toString(),
                    audit.date.toString(),
                    audit.description.toString(),

                )
            }?.let {
                dataSource.insert(
                    it
                )
            }

这就是我的班级现在的样子ApiDataSourceIMPL:

class ApiDataSourceIMPL (private val dataSource: RDDataSource):
    ApiDataSource {

    override fun startMigration (context: Context) {

    val call = ApiClient.instance?.api?.loadApi()
    call?.enqueue(object: Callback <ArrayList<Data>>
     {
        override fun onResponse(
            call: Call<ArrayList<Data>>,
            response: Response<ArrayList<Data>>
        ) {

            Log.d("ApiDataSource", "onResponse status: ${response.code()}")

            var loadNameList: ArrayList<Data>? = null

           // loadNameList?.clear()

            loadNameList = (response.body() as ArrayList<Data>?)!!
                  

            for (audit in loadNameList) {

                audit.id?.let {
                    PaginationLocalModel(
                        it,

                        audit.name.toString(),
                        audit.date.toString(),
                        audit.description.toString(),

                    )
                }?.let {
                    dataSource.insert(
                        it
                    )
                }

            }

            Toast.makeText(context, "ЗАГРУЗКА", Toast.LENGTH_SHORT).show()
        }

        override fun onFailure(call: Call <ArrayList<Data>>
   
                               , t: Throwable) {
            t.printStackTrace()
            Toast.makeText(context, "ОШИБКА! ВКЛЮЧИТЕ ИНТЕРНЕТ!", Toast.LENGTH_SHORT).show()
            Log.e("ApiDataSource2", "onFailure", t)
        }
    })

}

}

本地数据库模型:

@Entity(tableName = "pagination_table")
class PaginationLocalModel (

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "date")
    val date: String,

    @ColumnInfo(name = "description")
    val description: String

)

本地数据库:

@Database(entities = [PaginationLocalModel::class], version = 1)
abstract class ReceiveDataDB : RoomDatabase() {

    abstract val nameListDao : NameListDao
    abstract val descriptionDao : DescriptionDao

}
android
  • 0 个回答
  • 0 Views
Martin Hope
user462422
Asked: 2022-09-06 01:20:07 +0000 UTC

如何查找除扩展名为 .docx 的文件之外的所有文件?

  • 2

问题。告诉我如何在 Windows 资源管理器中查找具有 .docx 以外的任何扩展名的文件?

windows
  • 0 个回答
  • 0 Views
Martin Hope
user514769
Asked: 2022-08-31 22:03:06 +0000 UTC

使用 Retrofit 从 api 获取数据抛出 java.lang.IllegalStateException: 已经执行

  • -1

我正在写一个应用程序“汇率”。该应用程序实现了基础货币之间的切换,据此获得其他货币的汇率。基础货币之间的切换使用Spinner. 当我在启动应用程序后第一次切换到新货币时,一切正常,但是,一旦我返回到我已经收到并显示数据的货币,就会发生错误:

E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.sem.exchangerate, PID: 9209
        java.lang.IllegalStateException: Already executed.
            at retrofit2.OkHttpCall.enqueue(OkHttpCall.java:123)
            at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall.enqueue(DefaultCallAdapterFactory.java:78)
            at com.sem.exchangerate.data.dataSourceIMPL.ApiDataSourceIMPL.startMigration(ApiDataSourceIMPL.kt:25)
            at com.sem.exchangerate.data.repository.ExchangeRateRepository.startMigration(ExchangeRateRepository.kt:22)
            at com.sem.exchangerate.domain.useCase.ExchangeRateUseCase.startMigration(ExchangeRateUseCase.kt:21)
            at com.sem.exchangerate.presentation.viewModel.ExchangeRateViewModel$migration$1.invokeSuspend(ExchangeRateViewModel.kt:17)
            at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
            at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:367)
            at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
            at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
            at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
            at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
            at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
            at kotlinx.coroutines.BuildersKt.launch(Unknown Source:1)
            at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:47)
            at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source:1)
            at com.sem.exchangerate.presentation.viewModel.ExchangeRateViewModel.migration(ExchangeRateViewModel.kt:16)
            at com.sem.exchangerate.presentation.ExchangeRateFragment$onCreateView$6.onItemSelected(ExchangeRateFragment.kt:102)
            at android.widget.AdapterView.fireOnSelected(AdapterView.java:957)
            at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:946)
            at android.widget.AdapterView.access$300(AdapterView.java:55)
            at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:910)
            at android.os.Handler.handleCallback(Handler.java:938)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:223)
            at android.app.ActivityThread.main(ActivityThread.java:7697)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:952)
            Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@72fd5c2, Dispatchers.Main.immediate]

问题还在于数据每次都被覆盖,这意味着它们需要再次接收(我写这个与java.lang.IllegalStateException: Already executed错误文本中的行有关)

ApiDataSourceIMPL:

class ApiDataSourceIMPL(private val exchangeRateDataSource: ExchangeRateDataSource):
    ApiDataSource {

    companion object {
        var call: Call<ExchangeRateResponseModel>? = null
    }

    override fun startMigration (context: Context, dataApi: Call<ExchangeRateResponseModel>?) {

        call = dataApi
            // ApiClient.instance?.api?.loadExchangeRateApiUSD()
        call?.enqueue(object: Callback<ExchangeRateResponseModel> {
            override fun onResponse(
                call: Call<ExchangeRateResponseModel>,
                response: Response<ExchangeRateResponseModel>
            ) {

                Log.d("ApiDataSource", "onResponse status: ${response.code()}")
                // создаём список
                var loadExchangeRate: ExchangeRateResponseModel? = null
              //  loadExchangeRate?.clear()
                // получаем данные с сервера
                loadExchangeRate = (response.body() as ExchangeRateResponseModel?)!!

                exchangeRateDataSource.insert(ExchangeRateModel(1,"EUR", loadExchangeRate.rates?.EUR))
                exchangeRateDataSource.insert(ExchangeRateModel(2,"AUD", loadExchangeRate.rates?.AUD))
                exchangeRateDataSource.insert(ExchangeRateModel(3,"RUB", loadExchangeRate.rates?.RUB))
                exchangeRateDataSource.insert(ExchangeRateModel(4,"JPY", loadExchangeRate.rates?.JPY))
                exchangeRateDataSource.insert(ExchangeRateModel(5,"MDL", loadExchangeRate.rates?.MDL))

                Toast.makeText(context, "ЗАГРУЗКА", Toast.LENGTH_SHORT).show()
            }

            override fun onFailure(call: Call<ExchangeRateResponseModel>, t: Throwable) {
                Toast.makeText(context, "ОШИБКА! ВКЛЮЧИТЕ ИНТЕРНЕТ!", Toast.LENGTH_SHORT).show()
                Log.e("ApiDataSource2", "onFailure", t)
            }
        })

    }

}

API接口:

interface ApiInterface {

    @Headers("apikey: мой ключ") // вставь сюда ключ с этого сайта https://apilayer.com/marketplace/exchangerates_data-api#documentation-tab
    @GET("exchangerates_data/latest?symbols=AUD%2CEUR%2CJPY%2CMDL%2CRUB&base=USD")
    fun loadExchangeRateApiUSD(): Call<ExchangeRateResponseModel>

    @Headers("apikey: мой ключ") // вставь сюда ключ с этого сайта https://apilayer.com/marketplace/exchangerates_data-api#documentation-tab
    @GET("exchangerates_data/latest?symbols=AUD%2CEUR%2CJPY%2CMDL%2CRUB&base=RON")
    fun loadExchangeRateApiRON(): Call<ExchangeRateResponseModel>

    @Headers("apikey: мой ключ") // вставь сюда ключ с этого сайта https://apilayer.com/marketplace/exchangerates_data-api#documentation-tab
    @GET("exchangerates_data/latest?symbols=AUD%2CEUR%2CJPY%2CMDL%2CRUB&base=GBP")
    fun loadExchangeRateApiGBP(): Call<ExchangeRateResponseModel>

    @Headers("apikey: мой ключ") // вставь сюда ключ с этого сайта https://apilayer.com/marketplace/exchangerates_data-api#documentation-tab
    @GET("exchangerates_data/latest?symbols=AUD%2CEUR%2CJPY%2CMDL%2CRUB&base=KZT")
    fun loadExchangeRateApiKZT(): Call<ExchangeRateResponseModel>
}

ExchangeRateFragment 片段:

class ExchangeRateFragment : Fragment() {

    private var binding: FragmentExchangeRateBinding? = null
    private var exchangeRateAdapter : ExchangeRateAdapter? = null
    private val exchangeRateViewModel : ExchangeRateViewModel? by viewModel()
    private val favouriteViewModel: FavouriteViewModel by viewModel()

    private val dataApi: DataApi? = DataApi()

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

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_exchange_rate, container, false)

        initRecyclerExchangeRate()
        loadExchangeRate()

...

        ArrayAdapter.createFromResource(
            activity?.applicationContext!!,
            R.array.currency_array,
            android.R.layout.simple_spinner_item
        ).also { adapter ->

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

            binding?.spinner?.adapter = adapter
        }

        binding?.spinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {

                when(position) {
                    0 -> {
                        exchangeRateViewModel?.migration(requireContext(), dataApi?.apiUSD)
                        loadExchangeRate()
                    }
                    1 -> {
                        exchangeRateViewModel?.migration(requireContext(), dataApi?.apiRON)
                        loadExchangeRate()
                    }
                    2 -> {
                        exchangeRateViewModel?.migration(requireContext(), dataApi?.apiGBP)
                        loadExchangeRate()
                    }
                    3 -> {
                        exchangeRateViewModel?.migration(requireContext(), dataApi?.apiKZT)
                        loadExchangeRate()
                    }
                }
            }


            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

        }

        return binding?.root
    }

...

    private fun loadExchangeRate(){

        exchangeRateViewModel?.loadExchange?.observe(viewLifecycleOwner, Observer {

            exchangeRateAdapter?.setList(it)
            exchangeRateAdapter?.notifyDataSetChanged()
        })
    }
...
}
android
  • 1 个回答
  • 37 Views
Martin Hope
user515715
Asked: 2022-08-30 19:40:43 +0000 UTC

如何在 Fragment 中使用 Spinner?

  • 0

我在里面添加override fun onCreateView了这段代码:

 val array = arrayOf("Option 1", "Option 2", "Option 3")
    
            spinner = view?.findViewById<Spinner>(R.id.spinner)
            spinner?.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array)
    
            spinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                    //  result?.text = array.get(p2)
    
                    when(p2) {
                       // 0 -> result?.text = array.get(0)
                      //  1 -> result?.text = array.get(1)
                      //  2 -> result?.text = array.get(2)
                    }
                }
    
    
                override fun onNothingSelected(p0: AdapterView<*>?) {
                    // result?.text = array.get(0)
                }
    
            }

ArrayAdapter红色下划线

在此处输入图像描述

一切MainActivity正常。请告诉我如何制作它,以便片段内的所有内容也正常工作。

xml片段:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".presentation.ExchangeRateFragment">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.appcompat.widget.AppCompatSpinner
                android:id="@+id/spinner"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:ignore="MissingConstraints" />

            <LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                tools:ignore="MissingConstraints,RedundantNamespace">

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/sortAlphabetAscending"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_weight="1"
                android:layout_marginTop = "30dp"
                android:padding="20dp"
                android:background="@color/black"
                android:textColor="@color/white"
                android:text="@string/sortASC" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/sortAlphabetDescending"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_weight="1"
                android:layout_marginTop = "30dp"
                android:padding="20dp"
                android:background="@color/black"
                android:textColor="@color/white"
                android:text="@string/sortDESC" />

                <androidx.appcompat.widget.AppCompatButton
                    android:id="@+id/sortNumberAscending"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    android:layout_weight="1"
                    android:layout_marginTop = "30dp"
                    android:padding="20dp"
                    android:background="@color/black"
                    android:textColor="@color/white"
                    android:text="@string/sortNumberASC" />

                <androidx.appcompat.widget.AppCompatButton
                    android:id="@+id/sortNumberDescending"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent"
                    android:layout_weight="1"
                    android:layout_marginTop = "30dp"
                    android:padding="20dp"
                    android:background="@color/black"
                    android:textColor="@color/white"
                    android:text="@string/sortNumberDESC" />


            </LinearLayout>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/exchangeRateRV"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                android:layout_marginTop="90dp"
                app:layout_constraintTop_toBottomOf="@id/spinner"/>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </FrameLayout>

</layout>

方法onCreateView:

    private var binding: FragmentExchangeRateBinding? = null
    private var exchangeRateAdapter : ExchangeRateAdapter? = null
    private val exchangeRateViewModel : ExchangeRateViewModel? by viewModel()
    private val favouriteViewModel: FavouriteViewModel by viewModel()
    private var spinner : Spinner? = null

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

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_exchange_rate, container, false)

        initRecyclerExchangeRate()
        loadExchangeRate()

        binding?.sortAlphabetAscending?.setOnClickListener {

            exchangeRateViewModel?.getSortCurrencyAlphabetAscending?.observe(
                viewLifecycleOwner, Observer {
                    exchangeRateAdapter?.setList(it)
                    exchangeRateAdapter?.notifyDataSetChanged()
                }
            )
        }

        binding?.sortAlphabetDescending?.setOnClickListener {

            exchangeRateViewModel?.getSortCurrencyAlphabetDescending?.observe(
                viewLifecycleOwner, Observer {
                    exchangeRateAdapter?.setList(it)
                    exchangeRateAdapter?.notifyDataSetChanged()
                }
            )

        }

        binding?.sortNumberAscending?.setOnClickListener {

            exchangeRateViewModel?.getSortCurrencyNumberAscending?.observe(
                viewLifecycleOwner, Observer {
                    exchangeRateAdapter?.setList(it)
                    exchangeRateAdapter?.notifyDataSetChanged()
                }
            )

        }

        binding?.sortNumberDescending?.setOnClickListener {

            exchangeRateViewModel?.getSortCurrencyNumberDescending?.observe(
                viewLifecycleOwner, Observer {
                    exchangeRateAdapter?.setList(it)
                    exchangeRateAdapter?.notifyDataSetChanged()
                }
            )

        }

        val array = arrayOf("Option 1", "Option 2", "Option 3")

        val rootView = inflater.inflate(R.layout.fragment_exchange_rate, container, false)
        spinner = rootView.findViewById<Spinner>(R.id.spinner)

      //  spinner = view?.findViewById<Spinner>(R.id.spinner)
        
        spinner?.adapter =  ArrayAdapter<String>(requireContext(), android.R.layout.simple_list_item_1, array)
        
       // spinner?.adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

/*        ArrayAdapter.createFromResource(
            activity?.applicationContext!!,
            R.array.currency_array,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            // Apply the adapter to the spinner
            spinner?.adapter = adapter
        }*/

        spinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                //  result?.text = array.get(p2)

                when(p2) {
                   // 0 -> result?.text = array.get(0)
                  //  1 -> result?.text = array.get(1)
                  //  2 -> result?.text = array.get(2)
                }
            }


            override fun onNothingSelected(p0: AdapterView<*>?) {
                // result?.text = array.get(0)
            }

        }

        return binding?.root
    }
android
  • 1 个回答
  • 19 Views
Martin Hope
user515715
Asked: 2022-08-29 21:50:10 +0000 UTC

如何将 SSH 密钥令牌复制到命令行?

  • 0

命令行在使用时GitHub(或者更确切地说,当我尝试执行时git push)要求输入用户名和密码。在我这样做之后,以下崩溃:

Необработанное исключение: System.MissingMethodException: Метод не найден: "Void Microsoft.AzureRepos.AzureReposHostProvider..ctor(Microsoft.Git.CredentialManager.ICommandContext)".
       в Microsoft.Git.CredentialManager.Program.Main(String[] args)
    remote: Support for password authentication was removed on August 13, 2021.
    remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
    fatal: Authentication failed for 'https://github.com/NikolajTrenirovki/SpinnerAndroidKotlin.git/'

通过单击链接https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently,您可以发现您现在需要输入令牌而不是密码。问题是 ctrl c ctrl v 选项在这种情况下不起作用,命令行只是忽略插入并给出相同的错误(我也尝试手动输入,唉,结果相同)。

Важное уточнение:我正在尝试为位于我的第二个 github 帐户中的存储库推送更改,我通过第一个帐户在 cmd 中获得授权(我将第一个帐户添加到共同作者,这在之前就足够了)

git
  • 1 个回答
  • 55 Views
Martin Hope
user504975
Asked: 2022-08-27 23:16:58 +0000 UTC

哪个 css 文件具有更高的优先级?

  • 0

同事。

项目中有两个css文件。应该是什么连接顺序 - 哪个文件应该在上面/下面的头部,以便它具有更高的优先级?

谢谢

html
  • 1 个回答
  • 36 Views
Martin Hope
user515662
Asked: 2022-08-25 10:08:13 +0000 UTC

来自多维数组的两个不同答案

  • -1

我不明白需要添加什么才能显示 15 和 16,而不是 31。

也就是说,函数分别对数组的第一个元素和第二个元素求和。

我有一个添加数组所有元素的函数。

function numbers($massive){ 

$result = 0;

foreach($massive as $main){

foreach($main as $child){
$result = $result + $child;
}
}

return $result;
};


$massive = [

[1,2,3,4,5],
[1,2,3,4,6],

];

echo numbers($massive);

php
  • 1 个回答
  • 30 Views
Martin Hope
user515715
Asked: 2022-08-23 22:27:37 +0000 UTC

错误 IllegalStateException:应为 BEGIN_ARRAY 但为 BEGIN_OBJECT [关闭]

  • -1
关闭 这个问题是题外话。目前不接受回复。

该问题是由不再复制的问题或错字引起的。虽然类似问题可能与本网站相关,但该问题的解决方案不太可能帮助未来的访问者。通常可以通过在发布问题之前编写和研究一个最小程序来重现问题来避免此类问题。

22 天前关闭。

改进问题

有一个代码:

class ApiDataSourceIMPL(private val exchangeRateDataSource: ExchangeRateDataSource):
        ApiDataSource {
    
        override fun startMigration (context: Context) {
    
            val call = ApiClient.instance?.api?.loadExchangeRateApi()
            call?.enqueue(object: Callback<ArrayList<ExchangeRateApiModel>> {
                override fun onResponse(
                    call: Call<ArrayList<ExchangeRateApiModel>>,
                    response: Response<ArrayList<ExchangeRateApiModel>>
                ) {
                    // создаём список
                    var loadExchangeRate: ArrayList<ExchangeRateApiModel>? = null
                    // очищаем массив
                    loadExchangeRate?.clear()
                    // получаем данные с сервера
                    loadExchangeRate = (response.body() as ArrayList<ExchangeRateApiModel>?)!!
    
                    // помещение данных в локальную базу данных
                    for (audit in loadExchangeRate) {
    
                       // audit.id = 1
                        audit.id?.let {
                            ExchangeRateModel(
                                it,
                                audit.AUD.toString(),
                                audit.EUR.toString(),
                                audit.JPY.toString(),
                                audit.MDL.toString(),
                                audit.RUB.toString(),
    
                            )
                        }?.let {
                            exchangeRateDataSource.insert(
                                it
                            )
                        }
    
                    }
    
                    Toast.makeText(context, "ЗАГРУЗКА", Toast.LENGTH_SHORT).show()
                }
    
                override fun onFailure(call: Call<ArrayList<ExchangeRateApiModel>>, t: Throwable) {
                    Toast.makeText(context, "ОШИБКА! ВКЛЮЧИТЕ ИНТЕРНЕТ!", Toast.LENGTH_SHORT).show()
    
                }
            })
    
        }
    
    }

执行后,Toast 弹出ОШИБКА! ВКЛЮЧИТЕ ИНТЕРНЕТ!,尝试调试,仅到达行call?.enqueue(object: Callback<ArrayList<ExchangeRateApiModel>>(独占),然后转到“紧急”消息

请告诉我可能是什么原因造成的以及如何解决它。

ApiClient 代码:

class ApiClient private constructor() {

    val api: ApiInterface
        get() = retrofit!!.create(
            ApiInterface::class.java)

    init {
        retrofit =
            Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
                .build()

    }

    companion object {

        private val BASE_URL = "https://api.apilayer.com/"

        private var apiClient: ApiClient? = null
        private var retrofit: Retrofit? = null

        val instance: ApiClient?
            @Synchronized get() {

                if (apiClient == null) {

                    apiClient =
                        ApiClient()
                }

                return apiClient

            }
    }
}

获取请求:

@Headers("apikey: мой ключ")
@GET("exchangerates_data/latest?symbols=AUD%2CEUR%2CJPY%2CMDL%2CRUB&base=USD")
fun loadExchangeRateApi(): Call<ArrayList<ExchangeRateApiModel>>

包括互联网

<uses-permission android:name="android.permission.INTERNET" />在清单中是

甚至发送请求(在这个 api 中,每个月的请求数量是有限的,并且在应用程序启动后,计数器每次都会增加)

使用Log.e("ApiDataSource", "onFailure", t)得到:

2022-08-23 20:29:16.392 21052-21052/com.sem.exchangerate E/ApiDataSource: onFailure
    java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
        at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
        at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)

json:

{
  "base": "USD",
  "date": "2022-08-23",
  "rates": {
    "AUD": 1.444127,
    "EUR": 1.00345,
    "JPY": 136.770153,
    "MDL": 19.351829,
    "RUB": 60.249987
  },
  "success": true,
  "timestamp": 1661277305
}

接收型号:

data class ExchangeRateApiModel (

    @SerializedName("id") @Expose
    var id: Int? = 1,

    @SerializedName("AUD") @Expose
    val AUD: Double? = null,
    @SerializedName("EUR") @Expose
    val EUR: Double? = null,
    @SerializedName("JPY") @Expose
    val JPY: Double? = null,
    @SerializedName("MDL") @Expose
    val MDL: Double? = null,
    @SerializedName("RUB") @Expose
    val RUB: Double? = null

)

写入数据库的模型:

@Entity(tableName = "exchange_rate_table")
class ExchangeRateModel(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    val id:Int,

    @ColumnInfo(name = "AUD")
    val AUD: String,
    @ColumnInfo(name = "EUR")
    val EUR: String,
    @ColumnInfo(name = "JPY")
    val JPY: String,
    @ColumnInfo(name = "MDL")
    val MDL: String,
    @ColumnInfo(name = "RUB")
    val RUB: String

)

// 我试图只获取货币值

android json
  • 1 个回答
  • 33 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5