I am making a movies application in which i am fetching data from movie api and then storing it into database using content provider but when i try to get value from cursor it is not returning values: Here i checked values through debugging before inserting into database and they are not null but when i try to go in loop of cursor.moveToNext() it does not go in that loop. I am getting all uri from provider and data from net api correct but my cursor is not returning any values.
MainActivity.java:
public class MainActivity extends AppCompatActivity{
private int state;
private Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendData();
}
public void sendData() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String value = preferences.getString(getString(R.string.key), getString(R.string.value));
if (value.equalsIgnoreCase(getString(R.string.defaults))) {
state = 1;
uri = PopularMovie.CONTENT_URI;
} else if (value.equalsIgnoreCase(getString(R.string.defaults1))) {
state = 2;
uri = MovieContract.RatedMovie.CONTENT_URI;
}
//connectivity solver
if (myClickHandler()) {
//checking summary value
if (state==1) {
new Task().execute(Movie.getPopular());
} else if (state==2) {
new Task().execute(Movie.getRated());
}
}else{
new Data().execute();
}
}
//To check network connection
public boolean myClickHandler() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public class Task extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String jsonStr = null;
try {
// Construct the URL for the themoviedb query
//Building url
URL url = new URL(params[0]);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
jsonStr = buffer.toString();
Movie.getDataFromJson(jsonStr);
} catch (Exception e) {
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
return null;
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//setting adapter
GridView gridView = (GridView)findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(MainActivity.this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
saveData();
}
}
public void saveData(){
ContentValues[] values = new ContentValues[Movie.getTitle().size()];
if(state==1){
for(int i=0;i<Movie.getTitle().size();i++){
values[i] = new ContentValues();
values[i].put(PopularMovie.COLUMN_TITLE, Movie.getTitle().get(i));
values[i].put(PopularMovie.COLUMN_POSTER, Movie.getPoster().get(i));
values[i].put(PopularMovie.COLUMN_OVERVIEW, Movie.getOverview().get(i));
values[i].put(PopularMovie.COLUMN_RATING, Movie.getRating().get(i));
values[i].put(PopularMovie.COLUMN_DATE, Movie.getDate().get(i));
}
}
if(state==2){
for(int i=0;i<Movie.getTitle().size();i++){
values[i] = new ContentValues();
values[i].put(MovieContract.RatedMovie.COLUMN_TITLE, Movie.getTitle().get(i));
values[i].put(MovieContract.RatedMovie.COLUMN_POSTER, Movie.getPoster().get(i));
values[i].put(MovieContract.RatedMovie.COLUMN_OVERVIEW, Movie.getOverview().get(i));
values[i].put(MovieContract.RatedMovie.COLUMN_RATING, Movie.getRating().get(i));
values[i].put(MovieContract.RatedMovie.COLUMN_DATE, Movie.getDate().get(i));
}
}
int insert = this.getContentResolver().bulkInsert(uri, values);
}
public class Data extends AsyncTask<Void, Void,Void> {
@Override
protected Void doInBackground(Void... params) {
//get data
Cursor cursor = MainActivity.this.getContentResolver().query(uri, null, null, null, null);
while(cursor.moveToNext()) {
Movie.getTitle().add(cursor.getString(MovieContract.getColoumnIndex(PopularMovie.COLUMN_TITLE)));
Movie.getPoster().add(cursor.getString(MovieContract.getColoumnIndex(PopularMovie.COLUMN_POSTER)));
Movie.getOverview().add(cursor.getString(MovieContract.getColoumnIndex(PopularMovie.COLUMN_OVERVIEW)));
Movie.getRating().add(cursor.getInt(MovieContract.getColoumnIndex(PopularMovie.COLUMN_RATING)));
Movie.getDate().add(cursor.getString(MovieContract.getColoumnIndex(PopularMovie.COLUMN_DATE)));
}
MainActivity.this.getContentResolver().delete(uri,null,null);
cursor.close();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//setting adapter
GridView gridView = (GridView)findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(MainActivity.this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
This is my content provider class:
public class MovieProvider extends ContentProvider{
private SQLiteOpenHelper mOpenHelper;
private static final UriMatcher mUriMatcher;
private static final int POPULAR = 1;
private static final int POPULAR_TITLE = 2;
private static final int RATED = 3;
private static final int RATED_TITTE = 4;
static {
mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mUriMatcher.addURI(MovieContract.AUTHORITY, PopularMovie.TABLE_NAME, POPULAR );
mUriMatcher.addURI(MovieContract.AUTHORITY, PopularMovie.TABLE_NAME + "/*", POPULAR_TITLE );
mUriMatcher.addURI(MovieContract.AUTHORITY, MovieContract.RatedMovie.TABLE_NAME, RATED );
mUriMatcher.addURI(MovieContract.AUTHORITY, MovieContract.RatedMovie.TABLE_NAME + "/*", RATED_TITTE );
}
@Override
public boolean onCreate() {
mOpenHelper = new MovieData(getContext());
return true;
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase database = mOpenHelper.getReadableDatabase();
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
switch (mUriMatcher.match(uri)){
case POPULAR:{
builder.setTables(PopularMovie.TABLE_NAME);
break;
}
case RATED:{
builder.setTables(MovieContract.RatedMovie.TABLE_NAME);
break;
}
case POPULAR_TITLE:{
builder.setTables(PopularMovie.TABLE_NAME);
builder.appendWhere(PopularMovie.COLUMN_TITLE + " = " + uri.getLastPathSegment());
break;
}
case RATED_TITTE:{
builder.setTables(MovieContract.RatedMovie.TABLE_NAME);
builder.appendWhere(MovieContract.RatedMovie.COLUMN_TITLE + " = " + uri.getLastPathSegment());
break;
}
default:{
throw new IllegalArgumentException("Unsupported uri" + uri);
}
}
Cursor cursor = builder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Nullable
@Override
public String getType(Uri uri) {
switch (mUriMatcher.match(uri)){
case POPULAR: return PopularMovie.CONTENT_TYPE;
case POPULAR_TITLE: return PopularMovie.CONTENT_ITEM_TYPE;
case RATED: return MovieContract.RatedMovie.CONTENT_TYPE;
case RATED_TITTE: return MovieContract.RatedMovie.CONTENT_ITEM_TYPE;
default: return null;
}
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase database = mOpenHelper.getWritableDatabase();
Uri returnUri = null;
switch (mUriMatcher.match(uri)){
case POPULAR:{
long id = database.insert(PopularMovie.TABLE_NAME, null, values);
returnUri = MovieContract.getUriForId(uri, id);
break;
}
case RATED:{
long id = database.insert(MovieContract.RatedMovie.TABLE_NAME, null, values);
returnUri = MovieContract.getUriForId(uri, id);
break;
}
default:{
throw new SQLException("Unsupported Uri for insertion" + uri);
}
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase database = mOpenHelper.getWritableDatabase();
int id;
switch (mUriMatcher.match(uri)){
case POPULAR:{
id = database.delete(PopularMovie.TABLE_NAME, selection, selectionArgs);
break;
}
case RATED:{
id = database.delete(MovieContract.RatedMovie.TABLE_NAME, selection, selectionArgs);
break;
}
default:{
throw new SQLException("Unsupported Uri for deletion" + uri);
}
}
return id;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase database = mOpenHelper.getWritableDatabase();
int id;
switch (mUriMatcher.match(uri)){
case POPULAR:{
id = database.update(PopularMovie.TABLE_NAME, values, selection, selectionArgs);
break;
}
case RATED:{
id = database.update(MovieContract.RatedMovie.TABLE_NAME, values, selection, selectionArgs);
break;
}
default:{
throw new SQLException("Unsupported Uri for update" + uri);
}
}
if(id!=0){
getContext().getContentResolver().notifyChange(uri, null);
}
return id;
}
public int bulkInsert(Uri uri, ContentValues[] values){
SQLiteDatabase database = mOpenHelper.getWritableDatabase();
database.beginTransaction();
int inserted = 0;
switch (mUriMatcher.match(uri)){
case MovieProvider.POPULAR: {
try{
database.beginTransaction();
for (ContentValues value : values) {
long id = database.insert(PopularMovie.TABLE_NAME, null, value);
if (id != 0) {
inserted++;
}
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
break;
}
case MovieProvider.RATED: {
try{
database.beginTransaction();
for (ContentValues value : values) {
long id = database.insert(MovieContract.RatedMovie.TABLE_NAME, null, value);
if (id != 0) {
inserted++;
}
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
break;
}
}
return inserted;
}
}
This is my Contract class:
public class MovieContract {
//AUTHORITY
public static final String AUTHORITY = "com.example.sahilshokeen.movies";
//BASE URI
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
//get uri for id
public static Uri getUriForId(Uri uri, long id){
if(id>0){
return ContentUris.withAppendedId(uri, id);
}
throw new SQLException("Problem while inserting into uri" + uri);
}
public static int getColoumnIndex(String column){
if(column.equalsIgnoreCase(PopularMovie.COLUMN_TITLE)||column.equalsIgnoreCase(RatedMovie.COLUMN_TITLE)){
return 1;
}
if(column.equalsIgnoreCase(PopularMovie.COLUMN_POSTER)||column.equalsIgnoreCase(RatedMovie.COLUMN_POSTER)){
return 2;
}
if(column.equalsIgnoreCase(PopularMovie.COLUMN_OVERVIEW)||column.equalsIgnoreCase(RatedMovie.COLUMN_OVERVIEW)){
return 3;
}
if(column.equalsIgnoreCase(PopularMovie.COLUMN_RATING)||column.equalsIgnoreCase(RatedMovie.COLUMN_RATING)){
return 4;
}
if(column.equalsIgnoreCase(PopularMovie.COLUMN_DATE)||column.equalsIgnoreCase(RatedMovie.COLUMN_DATE)){
return 5;
}
return 1;
}
public static class PopularMovie implements BaseColumns{
//AUTHORITY
public static final String AUTHORITY = "com.example.sahilshokeen.movies";
//BASE URI
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
//Content uri
public static final Uri CONTENT_URI = BASE_URI.buildUpon().appendPath(PopularMovie.TABLE_NAME).build();
//MIME type of single item
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + AUTHORITY + "/" + PopularMovie.TABLE_NAME;
//MIME type of directory
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + AUTHORITY + "/" + PopularMovie.TABLE_NAME;
//table name
public static final String TABLE_NAME = "popular";
//title column
public static final String COLUMN_TITLE = "popular_title";
//poster column
public static final String COLUMN_POSTER = "popular_poster";
//overview column
public static final String COLUMN_OVERVIEW = "popular_overview";
//rating column
public static final String COLUMN_RATING = "popular_rating";
//date column
public static final String COLUMN_DATE = "popular_date";
}
public static class RatedMovie implements BaseColumns{
//AUTHORITY
public static final String AUTHORITY = "com.example.sahilshokeen.movies";
//BASE URI
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
//Content uri
public static final Uri CONTENT_URI = BASE_URI.buildUpon().appendPath(RatedMovie.TABLE_NAME).build();
//MIME type of single item
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + AUTHORITY + "/" + RatedMovie.TABLE_NAME;
//MIME type of directory
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + AUTHORITY + "/" + RatedMovie.TABLE_NAME;
//table name
public static final String TABLE_NAME = "rated";
//title column
public static final String COLUMN_TITLE = "rated_title";
//poster column
public static final String COLUMN_POSTER = "rated_poster";
//overview column
public static final String COLUMN_OVERVIEW = "rated_overview";
//rating column
public static final String COLUMN_RATING = "rated_rating";
//date column
public static final String COLUMN_DATE = "rated_date";
}
}
Aucun commentaire:
Enregistrer un commentaire