如何从数据库中无错误地获取图像?

如何从数据库中无错误地获取图像?,第1张

我使用Facebook登录,掌握配置文件图像,将其保存在DataBase中,然后尝试恢复DataBase图像,然后在ImageView中设置它,但它无效。

我想了解原因,也可能是解决方案。

来自Logcat的

错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.***/br.com.****}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access0(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0

的活动:

public class Perfil extends ActionBarActivity {

Database databaseHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_perfil);

    databaseHelper = new Database(this);
    TextView name = (TextView)findViewById(R.id.nameSurname);
    ImageView img = (ImageView)findViewById(R.id.imageTestePerfil);

    byte[] teste = databaseHelper.getImage();

    Bitmap bitmap = BitmapFactory. decodeByteArray(teste, 0, teste.length);

    img.setImageBitmap(bitmap);

}}

布局:

    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ff6600"
    tools:context="br.com.***.Perfil">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/imageTestePerfil"
        android:layout_below="@ id/app_bar"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="47dp" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name Surname"
        android:id="@ id/nameSurname"
        android:layout_marginTop="75dp"
        android:layout_below="@ id/imageTestePerfil"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Idade Perfil"
        android:id="@ id/idadePerfil"
        android:layout_below="@ id/nameSurname"
        android:layout_alignRight="@ id/textView8"
        android:layout_alignEnd="@ id/textView8" />

    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/ratingBar"
        android:layout_below="@ id/idadePerfil"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/imageView6"
        android:src="@drawable/progressbar"
        android:layout_below="@ id/ratingBar"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="7° colocado"
        android:id="@ id/textView7"
        android:layout_marginTop="62dp"
        android:layout_below="@ id/imageView6"
        android:layout_alignLeft="@ id/idadePerfil"
        android:layout_alignStart="@ id/idadePerfil" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="150 assertos"
        android:id="@ id/textView8"
        android:layout_below="@ id/textView7"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="52dp" />


</RelativeLayout>

数据库:

    public class Database {

DatabaseHelper helper;

public Database(Context context){
    helper = new DatabaseHelper(context);
}

public long insertData(String name, String idade, byte[] image){
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(DatabaseHelper.NAME, name);
    contentValues.put(DatabaseHelper.IDADE, idade);
    contentValues.put(DatabaseHelper.IMAGE, image);

    long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
    return id;
}


public byte[] getImage(){

    //select name, password from vivztable where name = 'anky';
    SQLiteDatabase db = helper.getWritableDatabase();
    String[] columns = {DatabaseHelper.IMAGE};
    Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
    StringBuffer buffer = new StringBuffer();



    byte[] personImage = cursor.getBlob(2); //////THIS LINE IS GIVING ERROR



    return personImage;
}


public String getAllData(){
    SQLiteDatabase db = helper.getWritableDatabase();
    String[] columns = {DatabaseHelper.UID, DatabaseHelper.NAME, DatabaseHelper.IDADE};
    Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
    StringBuffer buffer = new StringBuffer();

    while (cursor.moveToNext()){
        int cid = cursor.getInt(0);
        String name = cursor.getString(1);
        String idade = cursor.getString(2);
        buffer.append(cid "" name "" idade "\n");
    }
    return buffer.toString();
}

public String getName(){

    //select name, password from vivztable where name = 'anky';
    SQLiteDatabase db = helper.getWritableDatabase();
    String[] columns = {DatabaseHelper.NAME};
    Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
    StringBuffer buffer = new StringBuffer();
//DatabaseHelper.NAME " = '" name "'"
    cursor.moveToLast();
        int index1 = cursor.getColumnIndex(DatabaseHelper.NAME);
        String personName = cursor.getString(index1);
        buffer.append(personName);

    return buffer.toString();
}

public String getIdade(){

    //select name, password from vivztable where name = 'anky';
    SQLiteDatabase db = helper.getWritableDatabase();
    String[] columns = {DatabaseHelper.IDADE};
    Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
    StringBuffer buffer = new StringBuffer();
    //DatabaseHelper.NAME " = '" name "'"
    cursor.moveToLast();
    int index1 = cursor.getColumnIndex(DatabaseHelper.IDADE);
    String idade = cursor.getString(index1);
    buffer.append(idade);

    return buffer.toString();
}

static class DatabaseHelper extends SQLiteOpenHelper{

    private static final String UID = "_id";
    private static final String NAME = "name";
    private static final String IDADE = "idade";
    private static final String EMAIL = "email";
    private static final String IMAGE = "image";

    private static final String DATABASE_NAME = "perfildatabase";
    private static final String TABLE_NAME  = "PERFILTABLE";
    private static final int DATABASE_VERSION = 1;

    private static final String CREATE_TABLE = "create table "  TABLE_NAME   " (" UID " integer primary key autoincrement, "  NAME   " VARCHAR (255), "  IDADE   " VARCHAR (255), "  IMAGE   " BLOB);";

    private static final String DROP_TABLE = "DROP TABLE IF EXISTS " TABLE_NAME;

    private Context context;
    //MeuOpenHelper openHelper;
    //SQLiteDatabase db;

    public DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
        Message.message(context, "constructor called");
    }

    /**
     private class MeuOpenHelper extends SQLiteOpenHelper {
     MeuOpenHelper(Context context){
     super(context, NAME_BANCO, null, VERSAO_BANCO);

     }
     **/
    @Override
    public void onCreate(SQLiteDatabase db){
        try {
            db.execSQL(CREATE_TABLE);
            Message.message(context, "onCreate called");
        } catch (SQLException e){
            Message.message(context,"" e);
        }

    }


    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        try {
            db.execSQL(DROP_TABLE);
            onCreate(db);
            Message.message(context, "onUpgrade called");
        } catch (SQLException e){
            Message.message(context,"" e);
        }

    }

}
    }

使用Facebook登录代码:

public class MainFragment extends android.support.v4.app.Fragment {

private Database databaseHelper;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private TextView mTextDetails;
private ImageView imageTeste;
private CallbackManager mCallbackManager;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        displayWelcomeMessage(profile);


    }
    @Override
    public void onCancel() {
    }

    @Override
    public void onError(FacebookException e) {

    }
};
public MainFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();
    AccessTokenTracker tracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken old, AccessToken newToken) {

        }
    };

    ProfileTracker profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
            //displayWelcomeMessage(newProfile);
        }
    };
    tracker.startTracking();
    profileTracker.startTracking();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    LoginButton loginButton = (LoginButton)view.findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");
    loginButton.setFragment(this);
    loginButton.registerCallback(mCallbackManager, mCallback);

    //mTextDetails = (TextView) view.findViewById(R.id.text_details);
    imageTeste = (ImageView) view.findViewById(R.id.imageTeste);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_main, container, false);
}

public void displayWelcomeMessage(Profile profile){
    if (profile != null){

        databaseHelper = new Database(getActivity());
        String name = profile.getName();
        String idade = profile.getLastName();
        String userIds = profile.getId();


        Bitmap b = ((BitmapDrawable)imageTeste.getDrawable()).getBitmap();

        int bytes = b.getWidth()*b.getHeight()*4;


         ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
         b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer


         byte[] image = buffer.array();


         long id = databaseHelper.insertData(name, idade, image);
         if(id < 0){
         Message.message(getActivity(), "Unsuccessful");
         } else{
         Message.message(getActivity(), "Successfully Inserted a Row");
         }

    }

}


 public Bitmap getUserPic(String userID) {
 String imageURL;
 Bitmap bitmap = null;
 //Log.d(TAG, "Loading Picture");
 imageURL = "http://graph.facebook.com/" userID "/picture?type=small";
 try {
 bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
 } catch (Exception e) {
 Log.d("TAG", "Loading Picture FAILED");
 e.printStackTrace();
 }
 return bitmap;
 }


@Override
public void onResume() {
    super.onResume();
    Profile profile = Profile.getCurrentProfile();
    displayWelcomeMessage(profile);
}

@Override
public void onStop() {
    super.onStop();
    //mTokenTracker.stopTracking();
    //mProfileTracker.stopTracking();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}

最佳答案:

1 个答案:

答案 0 :(得分:0)

在访问之前将光标移动到开头:

public byte[] getImage(){

    SQLiteDatabase db = helper.getReadableDatabase();
    String[] columns = {DatabaseHelper.IMAGE};
    Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        return cursor.getBlob(cursor.getColumnIndex(DatabaseHelper.IMAGE));
    }
    return null;
}

并在访问返回值之前检查空值。

在您的活动中:

byte[] teste = databaseHelper.getImage();
if (teste != null) {
    Bitmap bitmap = BitmapFactory. decodeByteArray(teste, 0, teste.length);
    img.setImageBitmap(bitmap);
}
本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复