0

I have this custom Loader that is supposed to insert some dummy data I sent to it in a database using content resolver. I'm using the getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this); in the activity. The constructor gets called. But the onStartLoading() and loadinBackgroung() arent called.

Here is the ProductInsertionLoader.java

public class ProductInsertionLoader extends AsyncTaskLoader {
private String LOG_TAG = ProductInsertionLoader.class.getSimpleName();
private ArrayList<ContentValues> mValues;
private ContentResolver mContentResolver;

public ProductInsertionLoader(Context context, ContentResolver contentResolver, ArrayList<ContentValues> values) {
    super(context);
    mValues = values;
    mContentResolver = contentResolver;
    Log.v(LOG_TAG, "constructor called");
}

@Override
public Object loadInBackground() {
    Log.v(LOG_TAG, "loadInBackground() called");
    ArrayList<Uri> uris = new ArrayList<>();
    for (ContentValues value : mValues) {
        Uri uri = mContentResolver.insert(ProductContract.ProductEntry.CONTENT_URI, value);
        Log.v(LOG_TAG, "Dummy data inserted. ID: " + ContentUris.parseId(uri));
        uris.add(uri);
    }
    return null;
}

@Override
protected void onStartLoading() {
    Log.v(LOG_TAG, "onStartLoading() called");
    forceLoad();
}

}

Here is how I'm calling it in the CatalogActivity.java

package com.example.android.inventory;

import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.inventory.data.ProductContract.ProductEntry;
import com.example.android.inventory.data.ProductInsertionLoader;

import java.io.IOException;
import java.util.ArrayList;

public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String LOG_TAG = CatalogActivity.class.getSimpleName();
    private ProductCursorAdapter mCursorAdapter;
    private static final int URL_LOADER = 0;
    private static final int INSERT_DUMMY_DATA_ID = 1;
    private Uri mCurrentProductUri;
    private ArrayList<ContentValues> mValues;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_catalog);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
            startActivity(intent);
        }
    });

    final ListView listView = (ListView) findViewById(R.id.list_view_product);
    TextView textView = (TextView) findViewById(R.id.empty_view);
    listView.setEmptyView(textView);
    mCursorAdapter = new ProductCursorAdapter(this, null, getContentResolver());
    listView.setAdapter(mCursorAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
            Uri currentProductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
            intent.setData(currentProductUri);
            startActivity(intent);
        }
    });


    getLoaderManager().initLoader(URL_LOADER, null, CatalogActivity.this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_catalog, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_insert_dummy_data:
            insertDummyData();
            return true;
        case R.id.action_delete_all_entries:
            showDeleteConfirmationDialog("Delete all products?", null);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private void insertDummyData() {
    mValues = new ArrayList<>();
    mValues.add(getContentValues("Sugar", 50, 60, "Sweet Sugar Company", R.drawable.sugar));
    mValues.add(getContentValues("Salt", 20, 30, "Salty Salt Company", R.drawable.salt));
    mValues.add(getContentValues("Bread", 45, 20, "Nanglo", R.drawable.bread));
    mValues.add(getContentValues("Biscuit", 75, 20, "GoodDay", R.drawable.biscuit));
    mValues.add(getContentValues("Noodles", 15, 200, "CupMen", R.drawable.noodles));
    mValues.add(getContentValues("Milk", 33, 100, "DDC", R.drawable.milk));
    mValues.add(getContentValues("Cheese", 80, 30, "Amul", R.drawable.cheese));

    getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this).forceLoad();

    Toast.makeText(this, "Dummy Data Inserted", Toast.LENGTH_SHORT).show();
}

private ContentValues getContentValues(String name, int price, int quantity, String supplier, int resId) {
    ContentValues values = new ContentValues();
    values.put(ProductEntry.COLUMN_NAME, name);
    values.put(ProductEntry.COLUMN_PRICE, price);
    values.put(ProductEntry.COLUMN_QUANTITY, quantity);
    values.put(ProductEntry.COLUMN_SUPPLIER, supplier);

    //Uri for the sugar drawable
    Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
            "://" + getResources().getResourcePackageName(resId)
            + '/' + getResources().getResourceTypeName(resId)
            + '/' + getResources().getResourceEntryName(resId));
    Bitmap bitmap = null;
    //Converting the sugar image into a thumbnail
    try {
        bitmap = DbBitmapUtility.getThumbnail(imageUri, this);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Converting the sugar thumbnail into a byte array.
    byte[] image = DbBitmapUtility.getBitmapAsByteArray(bitmap);

    values.put(ProductEntry.COLUMN_IMAGE, image);
    return values;
}



@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    switch (id) {
        case URL_LOADER:
            String[] projection = {
                    ProductEntry._ID,
                    ProductEntry.COLUMN_NAME,
                    ProductEntry.COLUMN_QUANTITY,
                    ProductEntry.COLUMN_PRICE,
                    ProductEntry.COLUMN_SUPPLIER,
                    ProductEntry.COLUMN_IMAGE
            };
            return new CursorLoader(
                    this,
                    ProductEntry.CONTENT_URI,
                    projection,
                    null,
                    null,
                    null);
        case INSERT_DUMMY_DATA_ID:
            new ProductInsertionLoader(this, getContentResolver(), mValues);
            return null;
        default:
            Log.v(LOG_TAG, "onCreateLoader: Invalid id");
            return null;

    }
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (loader.getId() == URL_LOADER) {
        mCursorAdapter.swapCursor(data);
    } else return;
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    mCursorAdapter.swapCursor(null);

}

}

As you can see I'm using two loaders. One CursorLoader to load all the database data into the UI, and a second custom AsyncTaskLoader to insert some dummy data on to the database on a background thread. Why isn't the custom loader's onStartLoading() or loadInBackground() not being called?

Nissan
  • 466
  • 1
  • 4
  • 12
  • so you are calling `new ProductInsertionLoader(this, getContentResolver(), mValues);` and... ? it is not used anywhere... – pskink Jun 30 '17 at 06:41
  • Shouldn't that line call the AsyncTaskLoader and then it's onStartLoading() method followed by the loadInBackground() method? The loadInBackground has code to call the ContentProvider's insert method which also calls the notifyChange() method to update the UI. – Nissan Jun 30 '17 at 08:56
  • see what should be returned by onCreateLoader method – pskink Jun 30 '17 at 09:10
  • Right, that was one of my questions too. What do I do when I have multiple loaders that return different types of data? – Nissan Jun 30 '17 at 10:05

0 Answers0