mardi 1 mars 2016

Save data load from Api to Database in android

I use AsyncTask Load API from Server and Save to Database. private class GetDataAsync extends AsyncTask { private WeakReference mWeakReference; private boolean mErrorInternet = false; private List mApiFeedCurrent; public GetDataAsync(SplashActivity splashActivity) { mWeakReference = new WeakReference(splashActivity); }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {
        SplashActivity activity = mWeakReference.get();
        if (activity != null) {
            if (Utils.isInternetAvailable()) {
                try {
                    mApiFeedCurrent = activity.mApiService.getAllData();
                } catch (RetrofitError error) {
                    DebugTool.logD("ERROR = " + error.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mErrorInternet = true;
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        SplashActivity activity = mWeakReference.get();
        if (mErrorInternet && activity != null) {
            activity.alertDialog();
        } else {
            if (activity != null) {
                for (int i = 0; i < mApiFeedCurrent.size(); i++) {
                    int id = mApiFeedCurrent.get(i).getId();
                    String mediaName = mApiFeedCurrent.get(i).getMedia().getName();
                    String mediaUrl = mApiFeedCurrent.get(i).getMedia().getUrl();
                    String published = mApiFeedCurrent.get(i).getPublished();
                    String title = mApiFeedCurrent.get(i).getTitle();
                    String url = mApiFeedCurrent.get(i).getUrl();
                    String article = mApiFeedCurrent.get(i).getArticle();
                    String content = mApiFeedCurrent.get(i).getContent();
                    String imageUrl = mApiFeedCurrent.get(i).getImageUrl();
                    String href = mApiFeedCurrent.get(i).getListLinks().getSelf().getHref();
                    String audio_url = mApiFeedCurrent.get(i).getStream().getAudioUrl();
                    // save infor article to Article
                    Article art = new Article();
                    art.setId(id);
                    art.setMediaName(mediaName);
                    art.setMediaUrl(mediaUrl);
                    art.setPublished(published);
                    art.setTitle(title);
                    art.setUrl(url);
                    art.setArticle(article);
                    art.setContent(content);
                    art.setImageUrl(imageUrl);
                    art.setHref(href);
                    art.setAudioUrl(audio_url);
                    if (InformationTable.checkExists(mDatabase, InformationTable.TABLE_ARTICLE, id)) {
                        InformationTable.update(mDatabase, InformationTable.TABLE_ARTICLE, id, System.currentTimeMillis());
                    } else {
                        InformationTable.insertTable(mDatabase, InformationTable.TABLE_ARTICLE, id, mediaName, mediaUrl, published, title, url, article, content, imageUrl, href, audio_url);
                    }
                }

            }
            Intent intent = new Intent(SplashActivity.this, CategoryActivity.class);
            startActivity(intent);
            finish();
        }


    }

}

This is Model Article

public class Article {
private int id;
private String mediaName;
private String mediaUrl;
private String published;
private String title;
private String url;
private String article;
private String content;
private String imageUrl;
private String href;
private String audioUrl;

public Article(int id, String mediaName, String mediaUrl, String published, String title, String url, String article, String content, String imageUrl, String href, String audioUrl) {
    this.id = id;
    this.mediaName = mediaName;
    this.mediaUrl = mediaUrl;
    this.published = published;
    this.title = title;
    this.url = url;
    this.article = article;
    this.content = content;
    this.imageUrl = imageUrl;
    this.href = href;
    this.audioUrl = audioUrl;
}

public Article() {

}

public String getMediaUrl() {
    return mediaUrl;
}

public void setMediaUrl(String mediaUrl) {
    this.mediaUrl = mediaUrl;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getMediaName() {
    return mediaName;
}

public void setMediaName(String mediaName) {
    this.mediaName = mediaName;
}

public String getPublished() {
    return published;
}

public void setPublished(String published) {
    this.published = published;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public String getArticle() {
    return article;
}

public void setArticle(String article) {
    this.article = article;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getImageUrl() {
    return imageUrl;
}

public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
}

public String getHref() {
    return href;
}

public void setHref(String href) {
    this.href = href;
}

public String getAudioUrl() {
    return audioUrl;
}

public void setAudioUrl(String audioUrl) {
    this.audioUrl = audioUrl;
}
}

This is Database

 public class DatabaseDAO extends SQLiteOpenHelper {

// Database Verison
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "xxx.db";
private int mOpenCounter;
private SQLiteDatabase mDatabase;
private final static Object sDbLock = new Object();
private static DatabaseDAO instance;


public static synchronized DatabaseDAO getInstance(Context appContext) {
    if (instance == null) {
        synchronized (sDbLock) {
            if (instance == null) {
                instance = new DatabaseDAO(appContext);
            }
        }
    }
    return instance;
}

public DatabaseDAO(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    InformationTable.createTable(db, InformationTable.TABLE_ARTICLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

This is InformationTable

public class InformationTable {
public static final String TABLE_ARTICLE = "article";
public static final String TABLE_CATEGORY = "category";
public static final String COL_ID = "id";
public static final String COL_MEDIA_NAME = "media_name";
public static final String COL_MEDIA_URL = "media_url";
public static final String COL_PUBLISHED = "published";
public static final String COL_TITLE = "title";
public static final String COL_URL = "url";
public static final String COL_ARTICLE = "article";
public static final String COL_CONTENT = "content";
public static final String COL_IMAGE_URL = "image_url";
public static final String COL_HREF = "href";
public static final String COL_AUDIO_URL = "audio_url";
public static final String COL_CREATED_AT = "created_at";
public static final String COL_UPDATED_AT = "updated_at";

public static void createTable(SQLiteDatabase db, String tableName) {
    String sql =
            "CREATE TABLE " + tableName + " ("
                    + COL_ID + " INTEGER PRIMARY KEY NOT NULL, "
                    + COL_MEDIA_NAME + " TEXT, "
                    + COL_MEDIA_URL + " TEXT , "
                    + COL_PUBLISHED + " TEXT , "
                    + COL_TITLE + " TEXT, "
                    + COL_URL + " TEXT, "
                    + COL_ARTICLE + " TEXT, "
                    + COL_CONTENT + " TEXT, "
                    + COL_IMAGE_URL + " TEXT, "
                    + COL_HREF + " TEXT, "
                    + COL_AUDIO_URL + " TEXT, "
                    + COL_CREATED_AT + " INTEGER NOT NULL DEFAULT 0, "
                    + COL_UPDATED_AT + " INTEGER NOT NULL DEFAULT 0 "
                    + ")";

    db.execSQL(sql);
}


public static void delete(DatabaseDAO databaseDAO, String tableName, String where) {
    String sql = "DELETE FROM " + tableName;
    if (!TextUtils.isEmpty(where)) {
        sql += " WHERE " + where;
    }
    SQLiteDatabase database = databaseDAO.getReadableDatabase();
    database.execSQL(sql);
}

public static void insertTable(DatabaseDAO db, String tableName, int mId, String mediaName, String mediaUrl, String published, String title, String url, String article, String content, String imageUrl, String href, String audioUrl) {
    SQLiteDatabase database = db.getWritableDatabase();
    String sql =
            "INSERT INTO " + tableName + " ("
                    + COL_ID + ", "
                    + COL_MEDIA_NAME + ","
                    + COL_MEDIA_URL + ", "
                    + COL_PUBLISHED + ", "
                    + COL_TITLE + ", "
                    + COL_URL + ", "
                    + COL_ARTICLE + ", "
                    + COL_CONTENT + ", "
                    + COL_IMAGE_URL + ", "
                    + COL_HREF + ", "
                    + COL_AUDIO_URL + ", "
                    + COL_CREATED_AT + ","
                    + COL_UPDATED_AT +
                    ")"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    SQLiteStatement statement = database.compileStatement(sql);
    try {
        database.beginTransaction();
        statement.clearBindings();
        statement.bindLong(1, mId);
        statement.bindString(2, mediaName);
        statement.bindString(3, mediaUrl);
        statement.bindString(4, published);
        statement.bindString(5, title);
        statement.bindString(6, url);
        statement.bindString(7, article);
        statement.bindString(8, content);
        statement.bindString(9, imageUrl);
        statement.bindString(10, href);
        statement.bindString(11, audioUrl);
        statement.bindLong(12, System.currentTimeMillis());
        statement.bindLong(13, System.currentTimeMillis());
        database.setTransactionSuccessful();
    } catch (Exception e) {
        database.endTransaction();
    } finally {
        database.endTransaction();
    }

}


public static List<Article> getAll(DatabaseDAO databaseDAO, String tableName) {
    String sql = "SELECT * FROM " + tableName;
    SQLiteDatabase database = databaseDAO.getReadableDatabase();
    Cursor cursor = database.rawQuery(sql, null);
    return getAllCurrentFeed(cursor);
}

public static List<Article> getAllCurrentFeed(Cursor cursor) {
    List<Article> list = new ArrayList<>();
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(COL_ID));
                String mediaName = cursor.getString(cursor.getColumnIndex(COL_MEDIA_NAME));
                String mediaUrl = cursor.getString(cursor.getColumnIndex(COL_MEDIA_URL));
                String published = cursor.getString(cursor.getColumnIndex(COL_PUBLISHED));
                String title = cursor.getString(cursor.getColumnIndex(COL_TITLE));
                String url = cursor.getString(cursor.getColumnIndex(COL_URL));
                String article = cursor.getString(cursor.getColumnIndex(COL_ARTICLE));
                String content = cursor.getString(cursor.getColumnIndex(COL_CONTENT));
                String imageUrl = cursor.getString(cursor.getColumnIndex(COL_IMAGE_URL));
                String href = cursor.getString(cursor.getColumnIndex(COL_HREF));
                String audio_url = cursor.getString(cursor.getColumnIndex(COL_AUDIO_URL));
                Article art = new Article(id, mediaName, mediaUrl, published, title, url, article, content, imageUrl, href, audio_url);
                list.add(art);
            } while (cursor.moveToNext());
        }
        if (!cursor.isClosed()) {
            cursor.close();
        }
    }
    return list;
}

public static boolean checkExists(DatabaseDAO databaseDAO, String tableName, int id) {
    Cursor cursor = databaseDAO.getReadableDatabase().rawQuery("SELECT * FROM " + tableName + " WHERE " + COL_ID + " = " + id, null);
    if (cursor.getCount() > 0) {
        cursor.close();
        return true;
    }
    cursor.close();
    return false;
}

public static void update(DatabaseDAO databaseDAO, String tableName, int id, long time) {
    SQLiteDatabase database = databaseDAO.getWritableDatabase();
    String sql =
            "UPDATE " + tableName + " SET "
                    + COL_UPDATED_AT + " = " + time
                    + " WHERE " + COL_ID + " = " + id;
    database.execSQL(sql);
}

public static void deleteDataOlderThan30Days(SQLiteDatabase database, String tableName) {


    String sql = "DELETE FROM " + tableName + " WHERE " + COL_ID + "<= date('now','-30 day')";
    database.execSQL(sql);
}
}

This is CategoryActivity

public class CategoryActivity extends BaseActivity implements View.OnClickListener {
private ImageView mImageHome;
private ImageView mImageRight;
private List<Article> mListArticle;
DatabaseDAO mDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category);
    mDatabase = DatabaseDAO.getInstance(getApplicationContext());
    addControl();
    addEventOnClick();
    mListArticle = InformationTable.getAll(mDatabase, InformationTable.TABLE_ARTICLE);

    for (Article art : mListArticle) {
        DebugTool.logD("DATABASE ID " + art.getId());
        DebugTool.logD("DATABASE Title " + art.getTitle());
        DebugTool.logD("DATABASE imageurl " + art.getImageUrl());

    }


}

My code not working . Please. Help me!

Aucun commentaire:

Enregistrer un commentaire