The best way to insert jsonArray elements into the book in ActiveAndroid with a for statement

Asked 1 years ago, Updated 1 years ago, 91 views

ActiveAndroid is bothering me because I don't know how to insert data.

book.title="Book"; 
book.save(); 

I understand that it will be inserted as above, but I'm thinking about how to insert data into the model.

Thank you for your cooperation.

public static void jsonParse(){

    newDelete().from(Book.class).execute();
    ActiveAndroid.beginTransaction();

    try{
        AndroidTestActivity.mContext=app.getContext();

        AssetManager assetManager=mContext.getAssets();

        InputStream inputStream=assetManager.open(FILE_NAMES);

        JsonReader jsonReader = new JsonReader (new InputStreamReader (inputStream);
        Gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray jArray=parser.parse(jsonReader).getAsJsonArray();

        Bookbook=newBook();
        /** How to insert here*/
        book.title= 
        book.author= 
        book.publisher= 
        book.releaseDate= 

        book.save();

    } catch(IOExceptione){
        e.printStackTrace();
    }
    US>finally
        ActiveAndroid.setTransactionSuccessful();
    }
    ActiveAndroid.endTransaction();
}

Book.java

@Table(name="Book")
        public class Book extensions Model {
            private static final String TAG = Book.class.getSimpleName();

            @Column(name="title")
            public String title;

            @Column(name="author")
            public String author;

            @Column(name="publisher")
            public String publisher;

            @Column(name="release_date")
            public String releaseDate;

            publicBook(){
                super();
            }
            publicBook(String title, String author, String publisher, String date) {
                super();
                This.title=title;
                this.author = author;
                This.publisher=publisher;
                This.releaseDate=date;
            }

            public static Book fromJson(JSONObject jsonObject){
                Book book = new Book();

                try{
                    b. title=jsonObject.getString("title");
                    b.author=jsonObject.getString("author");
                    b.publisher=jsonObject.getString("publisher");
                    b.releaseDate=jsonObject.getString("release_date");
                    b.save();
                }catch(JSONExceptione){
                    e.printStackTrace();
                    return null;
                }
                // return new object
                return b;
            }
        }

android json sqlite

2022-09-30 19:30

1 Answers

Using the acquired JsonArray, you should do the following:

for(inti=0;i<jArray.length();i++){
   Book.fromJson(jArray.getJSONObject(i)));
}


2022-09-30 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.