当前位置: 首页 > 知识库问答 >
问题:

如何修复由以下原因引起的Async任务错误:java.lang.数字格式异常:对于输入字符串:“宠物”

轩辕亮
2023-03-14

我得到了这个错误:

​原因:java。lang.NumberFormatException:对于输入字符串:“pets”,在尝试将html" target="_blank">数据插入数据库时。当点击mainActivity上的insert选项时,它应该将数据插入数据库,并将数据显示到mainActivity中,但由于错误,我的应用程序正在崩溃。如何解决这个错误?该错误是在选择参数点的PetProvider查询的Pet_ID中引起的。

PetProvider的代码如下所示:

`2021-12-12 02:21:07.435 11934-11959/com。实例myapplication E/AndroidRuntime:致命异常:AsyncTask#1
进程:com。实例myapplication,PID:11934

java.lang.运行时异常:执行doInbackground()时发生错误

在Android。操作系统。4美元。在java上完成(AsyncTask.java:415)
。util。同时发生的未来任务。在java上完成(FutureTask.java:383)
。util。同时发生的未来任务。setException(FutureTask.java:252)
在java上。util。同时发生的未来任务。在java上运行(FutureTask.java:271)
。util。同时发生的线程池执行器。java上的runWorker(ThreadPoolExecutor.java:1167)
。util。同时发生的ThreadPoolExecutor$Worker。在java上运行(ThreadPoolExecutor.java:641)
。朗。丝线。运行(Thread.java:923)

原因:java。lang.NumberFormatException:用于输入字符串:“pets”

java.lang.Long.parseLong(Long.java:594)
atjava.lang.Long.parseLong(Long.java:636)
atandroid.content.ContentUris.parseId(ContentUris.java:89)
atcom.example.myapplication.data.PetProvider.query(PetProvider.java:100)
atandroid.content.ContentProvider.query(ContentProvider.java:1379)
atandroid.content.ContentProvider.query(ContentProvider.java:1475)
atandroid.content.ContentProvider$Transport.query(ContentProvider. java: 278)
at android. content.ContentResolver. Query(ContentResolver. java: 1185)
在android. content. ContentResolver. Query(ContentResolver. java: 1116)
在android. content. CursorLoader. loadInbackground(CursorLoader. java: 71)
在android. content. CursorLoader. loadInbackground(CursorLoader. java: 46)
在android. content. AsyncTaskLoader. onLoadInbackground(AsyncTaskLoader. java: 321)在android. content. AsyncTaskLoader$LoadTask. doInbackground(AsyncTaskLoader. java: 74)在android. content. AsyncTaskLoader$LoadTask. doInbackground(AsyncTaskLoader. java: 62)在android. os. AsyncTask3 Dollar

    import android.content.ContentProvider;
    import android.content.ContentResolver;
    import android.content.ContentUris;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.UriMatcher;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.net.Uri;
    import android.util.Log;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    
    import java.nio.file.Path;
    
    
    public class PetProvider extends ContentProvider {
    
        private PetdbHepler petdbHepler;
        public static String CONTENT_AUTHORITY = "com.example.myapplication";
    
        //To make this a usable URI, we use the parse method which takes in a URI string and returns a Uri.
        public static Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
    
        //This constants stores the path for each of the tables which will be appended to the base content URI.
    
        public static final String PATH_PETS = "pets";
    
        public static final String LOG_TAG = PetProvider.class.getSimpleName();
    
    
        /**
         * URI matcher code for the content URI for the pets table
         */
        private static final int PETS = 100;
    
        /**
         * URI matcher code for the content URI for a single pet in the pets table
         */
        private static final int PET_ID = 101;
    
        /**
         * UriMatcher object to match a content URI to a corresponding code.
         * The input passed into the constructor represents the code to return for the root URI.
         * It's common to use NO_MATCH as the input for this case.
         */
        private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
        // Static initializer. This is run the first time anything is called from this class.
        static {
            // The calls to addURI() go here, for all of the content URI patterns that the provider
            // should recognize. All paths added to the UriMatcher have a corresponding code to return
            // when a match is found.
    
            sUriMatcher.addURI(CONTENT_AUTHORITY, PATH_PETS, PETS);
            sUriMatcher.addURI(CONTENT_AUTHORITY, PATH_PETS + "/#", PET_ID);
    
        }
    
    
        @Override
        public boolean onCreate() {
            petdbHepler = new PetdbHepler(getContext());
            return false;
        }
    
        @Nullable
        @Override
        public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
            //steps To follow to query the database
            //first we nedd to get access to the database
            //second we need to pass the uri and check if the query is for whole table or for a single pet using uri matcher
            //atlast we need to switch according to the uri
            // so here is our code
    
            SQLiteDatabase database = petdbHepler.getReadableDatabase(); /*since we are only querying the database we need to use
                                                           getReadableDatabase and this step is to access the database which is first step*/
            Cursor cursor;
            int matcher = sUriMatcher.match(uri);//second we need to pass the uri and check if the query is for whole table or for a single pet using uri matcher
            switch (matcher) {
                case PETS:
                    cursor = database.query(Petcontract.PetsEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
                case PET_ID:
                    // For the PET_ID code, extract out the ID from the URI.
                    // For an example URI such as "content://com.example.android.pets/pets/3",
                    // the selection will be "_id=?" and the selection argument will be a
                    // String array containing the actual ID of 3 in this case.
                    //
                    // For every "?" in the selection, we need to have an element in the selection
                    // arguments that will fill in the "?". Since we have 1 question mark in the
                    // selection, we have 1 String in the selection arguments' String array.
    
    
                    selection = Petcontract.PetsEntry._ID + "?";
                    selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                    cursor = database.query(Petcontract.PetsEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
                    Log.e("PetProvider", "Hereis the problem");
                    break;
                default:
                    throw new IllegalArgumentException("cannot query unknown uri" + uri);
            }
            // Set notification URI on the Cursor,
            // so we know what content URI the Cursor was created for.
            // If the data at this URI changes, then we know we need to update the Cursor
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
            return cursor;
        }
    
        @Nullable
        @Override
        public String getType(@NonNull Uri uri) {
            return null;
        }
    
        @Nullable
        @Override
        public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
            final int match = sUriMatcher.match(uri);
            switch (match) {
                case PETS:
                    return insertPet(uri, contentValues);
                default:
                    throw new IllegalArgumentException("Insertion is not supported for " + uri);
            }
        }
    
       private Uri insertPet(Uri uri, ContentValues contentValues){
           // Check that the name is not null
           String name = contentValues.getAsString(Petcontract.PetsEntry.COLUMN_NAME);
           if (name == null) {
               throw new IllegalArgumentException("Pet requires a name");
           }
    
           // Check that the gender is valid
           Integer gender = contentValues.getAsInteger(Petcontract.PetsEntry.COLUMN_GENDER);
           if (gender == null) {
               throw new IllegalArgumentException("Pet requires valid gender");
           }
    
           // If the weight is provided, check that it's greater than or equal to 0 kg
           Integer weight = contentValues.getAsInteger(Petcontract.PetsEntry.COLUMN_WEIGHT);
           if (weight != null && weight < 0) {
               throw new IllegalArgumentException("Pet requires valid weight");
           }
            SQLiteDatabase sqLiteDatabase = petdbHepler.getWritableDatabase();
            long id = sqLiteDatabase.insert(Petcontract.PetsEntry.TABLE_NAME, null, contentValues);
           // Notify all listeners that the data has changed for the pet content URI
           getContext().getContentResolver().notifyChange(uri, null);
    
           return  ContentUris.withAppendedId(Petcontract.PetsEntry.content_uri, id);
       }
    
    
        @Override
        public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
            // Get writeable database
            SQLiteDatabase database =petdbHepler.getWritableDatabase();
            int rowsDeleted;
            final int match = sUriMatcher.match(uri);
            switch (match) {
                case PETS:
                    // Delete all rows that match the selection and selection args
                    return database.delete(Petcontract.PetsEntry.TABLE_NAME, selection, selectionArgs);
                case PET_ID:
                    // Delete a single row given by the ID in the URI
                    selection = Petcontract.PetsEntry._ID + "=?";
                    selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
                    rowsDeleted = database.delete(Petcontract.PetsEntry.TABLE_NAME, selection, selectionArgs);
                    // If 1 or more rows were deleted, then notify all listeners that the data at the
                    // given URI has changed
                    if (rowsDeleted != 0) {
                        getContext().getContentResolver().notifyChange(uri, null);
                        return database.delete(Petcontract.PetsEntry.TABLE_NAME, selection, selectionArgs);
                    }
                    else{
                        return rowsDeleted;
                    }
                default:
                    throw new IllegalArgumentException("Deletion is not supported for " + uri);
            }
    
        }
    
        @Override
        public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
            SQLiteDatabase database = petdbHepler.getWritableDatabase();
            int rowsUpdated = database.update(Petcontract.PetsEntry.TABLE_NAME, values, selection, selectionArgs);
    
            if (rowsUpdated != 0) {
                getContext().getContentResolver().notifyChange(uri, null);
                return rowsUpdated;
            }
            else
            {
                return database.update(Petcontract.PetsEntry.TABLE_NAME, values, selection, selectionArgs);
            }
        }
    }`

共有1个答案

平庆
2023-03-14
Just add break after the case: Pet. The code is;
   case PETS:
                cursor = database.query(Petcontract.PetsEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
                break;  //dont't forget to add break statement in Pet case.
            case PET_ID:
 类似资料:
  • 我的代码过早地抛出了预期错误。我试图测试输入验证,但在验证发生之前我抛出了一个错误。当我尝试将代码恢复到以前的版本时,它会抛出与我现在处理的问题之前相同的错误。 输入的示例 下面的代码是第137行——明显的罪犯 这是一个例外。

  • 我正在用一种形式做一个简单的插入。 no_text dbname_m_db 我想回去看看。所以我要做4个测试,它们是 测试1:插入no_text 测试2:插入no_text_external 测试3:不插入任何文本 测试4:不同时插入两个 所以结果是,只有test3是成功地查看它。而其他3返回错误号格式例外:对于输入字符串:""。我不知道过滤它的最佳方法。这里的代码,我的工作。任何想法?

  • 我正在用android Studio开发扫描android应用程序的蓝牙设备。有一个输入字段,当输入名称与扫描名称匹配时,我想将数据发送到firebase。下面我已经提到了我在做什么 } 当我运行应用程序时,应用程序已停止,出现如下错误 我能做些什么来避免NumberFormatException

  • 我有一张这样的地图 我可以得到分数作为整数以及"NA",所以我映射类型为字符串,但在发布数据到索引我得到数字格式异常。 例如: 如果我将第一个数据发布为整数,后跟“NA”。我得到了这些例外。 检查日志文件时,我发现以下错误: [2016-08-29 15:19:01]elasticlog.警告:响应[{\"错误\":{\"root_cause类型\":\"mapper_parsing_except

  • 我试图运行此代码,但它发生错误。 正如我们所知,长的最小数量是-9,223,372,036,854,775,808和0x9000000000000000-8,070,450,532,247,928,832为什么会发生错误?

  • 当前正在编辑代码以创建跳过列表,我正在尝试读取一个文件,其中包含需要插入、搜索或删除的数据(分别由i、s、d表示)。 当试图运行它时,我被抛出数字格式异常,当它在catch语句中打印堆栈跟踪时,它看起来好像没有读取第一个字符,应该是“i”。 以下是我的主代码当前的样子,因为这似乎就是问题所在 这是我的示例输入数据文本文件的样子 当它运行并吐回堆栈跟踪时,它会说 所以我现在猜测,出于某种原因,当50