SQLite에 이미지를 저장하는 방법과 입력 텍스트 및 이미지를 표 형식으로 내보내는 방법은 무엇입니까?

히만 슈

1) 버튼으로 제출 한 이미지를 SQLite에 저장하도록 도와주세요.

2) 내 앱에서 내보내기 기능을 구현하여 SQLite에 저장된 모든 입력 텍스트와 이미지를 어떤 형식으로도 내보낼 수 있지만 내 보낸 파일을 다시 데이터 검색에 사용할 수 있도록 표 형식으로 내보낼 수 있습니다.

DatabaseHelper.java

package com.example.himanshu.instrumentalinformationcollector;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "instruments.db";
private static final String TABLE_NAME = "instrument_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LOCATION";
public static final String COL_4 = "INFORMATION";

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

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    String CREATE_TABLE="CREATE TABLE " + DatabaseHelper.TABLE_NAME + " (" +
            DatabaseHelper.COL_1 + " INTEGER,"
            + DatabaseHelper.COL_2  + " TEXT,"
            + DatabaseHelper.COL_3 + " TEXT,"
            + DatabaseHelper.COL_4 + " TEXT);";
    sqLiteDatabase.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +DatabaseHelper.TABLE_NAME);
    onCreate(sqLiteDatabase);

}
public boolean insertData(Integer ID, String name, String location, String information){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();

    contentValues.put(DatabaseHelper.COL_1,ID);
    contentValues.put(DatabaseHelper.COL_2,name);
    contentValues.put(DatabaseHelper.COL_3,location);
    contentValues.put(DatabaseHelper.COL_4,information);

    sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME,null,contentValues);
    return true;
}
}

MainActivity.java

package com.example.himanshu.instrumentalinformationcollector;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.FileDescriptor;
import java.io.IOException;

public class MainActivity extends AppCompatActivity{
private static int RESULT_LOAD_IMAGE = 1;
DatabaseHelper myDB;
EditText editMessage,editMessage1,editMessage2,editMessage3;
Button submitData;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button buttonLoadImage = (Button)findViewById(R.id.imgButton);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
    myDB = new DatabaseHelper(this);

    editMessage=(EditText)findViewById(R.id.editText);
    editMessage1=(EditText)findViewById(R.id.editText1);
    editMessage2=(EditText)findViewById(R.id.editText2);
    editMessage3=(EditText)findViewById(R.id.editText3);
    submitData=(Button)findViewById(R.id.submit);
    AddData();

}

public void AddData(){
    submitData.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    boolean isInserted = myDB.insertData(Integer.valueOf(editMessage.getText().toString()),editMessage1.getText().toString(),editMessage2.getText().toString(),editMessage3.getText().toString());
                if(isInserted == true)
                    Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    else
                    Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
                }
            }
    );
}

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.img);

        Bitmap bmp = null;

        try {
            bmp = getBitmapFromUri(selectedImage);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        imageView.setImageBitmap(bmp);

    }


}

private Bitmap getBitmapFromUri(Uri uri) throws IOException {
    ParcelFileDescriptor parcelFileDescriptor =
            getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    parcelFileDescriptor.close();
    return image;
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
        tools:context="com.example.himanshu.instrumentalinformationcollector.MainActivity">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:layout_alignParentLeft="true"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ID"
            android:id="@+id/textView"
            android:textColor="@android:color/black"
            />
        <ImageView
            android:layout_alignParentRight="true"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/img"
            android:background="@drawable/gray"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp"
            />
        <Button
            android:layout_alignParentRight="true"
            android:layout_below="@id/img"
            android:layout_marginRight="10dp"
            android:id="@+id/imgButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:text="Upload"
            android:textSize="16sp"
            />
        <EditText
            android:layout_marginTop="15dp"
            android:id="@+id/editText"
            android:layout_toRightOf="@id/textView"
            android:layout_toLeftOf="@id/imgButton"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="45sp"
            android:layout_marginRight="30sp"
            android:hint="Please enter here"
            android:maxLength="6"
            android:textSize="16sp"
            android:inputType="number"
            />
        <TextView
            android:layout_alignParentLeft="true"
            android:layout_below="@id/textView"
            android:layout_marginTop="50dp"
            android:layout_marginLeft="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textSize="16sp"
            android:id="@+id/textView1"
            android:textColor="@android:color/black"
            />
        <EditText
            android:id="@+id/editText1"
            android:layout_marginTop="30dp"
            android:layout_below="@id/editText"
            android:layout_toRightOf="@id/textView1"
            android:layout_toLeftOf="@id/imgButton"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16sp"
            android:hint="Full Name"
            android:textSize="16sp"
            android:inputType="textCapWords"
            />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <TextView
            android:layout_marginTop="5dp"
            android:layout_marginLeft="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Location"
            android:textSize="16sp"
            android:id="@+id/textView3"
            android:textColor="@android:color/black"
            />
        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="Please enter here"
            android:textSize="16sp"
            android:inputType="textCapSentences"
            android:layout_weight="1"
            />
    </LinearLayout>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">
    <TextView
        android:layout_marginTop="16dp"
        android:layout_marginLeft="16sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Information"
        android:textSize="16sp"
        android:id="@+id/textView2"
        android:textColor="@android:color/black"
        />
    <EditText
        android:layout_alignParentLeft="true"
        android:layout_toRightOf="@id/textView2"
        android:layout_below="@id/textView2"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="16sp"
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine|textCapSentences"
        android:gravity="top"
        android:hint="Describe briefly"
        android:textSize="16sp"
        >
    </EditText>
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Submit"
            android:layout_weight="1"
            android:layout_marginRight="16dp"
            android:layout_marginLeft="16dp"
            />

        <Button
            android:id="@+id/export"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Export"
            android:layout_weight="1"
            android:layout_marginRight="16dp"
            android:layout_marginLeft="16dp"/>
    </LinearLayout>
</LinearLayout>

Apelsoczi

귀하의 질문에 대한 답변은 길며 많은 변경이 필요합니다.

이미지 저장 :

  • 이미지를 저장하려면 이미지를 바이트 배열로 변환해야합니다.
  • 더 실행 가능한 접근 방식은 이미지를 앱의 내부 저장소 내에 파일로 저장하고 데이터베이스에 열을 추가하여 공통 디렉토리 "s8u903wmips.jpg"에 이미지 이름을 저장하는 것입니다.

데이터 내보내기 :

  • 콘텐츠 제공자는 정확히 이러한 이유로 만들어집니다. https://developer.android.com/guide/topics/providers/content-providers.html
  • 콘텐츠 제공자는 Android 애플리케이션의 기본 구성 요소 중 하나로서 애플리케이션에 콘텐츠를 제공합니다. 이들은 데이터를 캡슐화하고 단일 ContentResolver 인터페이스를 통해 애플리케이션에 제공합니다. 콘텐츠 제공자는 여러 애플리케이션간에 데이터를 공유해야하는 경우에만 필요합니다. 예를 들어 연락처 데이터는 여러 애플리케이션에서 사용되며 콘텐츠 제공 업체에 저장되어야합니다. 여러 애플리케이션간에 데이터를 공유 할 필요가없는 경우 SQLiteDatabase를 통해 직접 데이터베이스를 사용할 수 있습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관