我正在尝试使用片段将我的图像发送到数据库。最初,下面的代码与活动配合得很好但是当我使用片段时它不是创建数据库而是创建了一个新文件夹app_downloads,其中我的图像保存在png中格式。我试过的代码是 -
public class MainFragment extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_fragment);
//ButtonFragment buttonfrag=new ButtonFragment();
//NumericFragment numericfrag=new NumericFragment();
CaptureSignature capture=new CaptureSignature();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
//transaction.add(R.id.buttonframelayout,buttonfrag,"button");
transaction.add(R.id.emailframelayout,capture,"button");
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main_fragment, menu);
return true;
}
}
public class CaptureSignature extends Fragment implements OnClickListener {
LinearLayout mContent;
signature mSignature;
Button mClear, mGetSign, mCancel;
public static String tempDir;
public int count = 1;
public String current = null;
private Bitmap mBitmap;
View mView;
File mypath;
Context context;
private String uniqueId;
private EditText yourName;
public DatabaseMethods db;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
db=new DatabaseMethods(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View viewFrag = inflater.inflate(R.layout.signature, container, false);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// DatabaseMethods db=new DatabaseMethods(this);
tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
ContextWrapper cw = new ContextWrapper(getActivity());
File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
prepareDirectory();
uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
current = uniqueId + ".png";
mypath= new File(directory,current);
Log.e("path"," "+mypath);
mContent = (LinearLayout)viewFrag. findViewById(R.id.linearLayout);
mSignature = new signature(getActivity(), null);
mSignature.setBackgroundColor(Color.WHITE);
mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mClear = (Button)viewFrag.findViewById(R.id.clear);
mGetSign = (Button)viewFrag.findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button)viewFrag.findViewById(R.id.cancel);
mView = mContent;
yourName = (EditText)viewFrag.findViewById(R.id.yourName);
mClear.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});
mGetSign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Saved");
boolean error = captureSignature();
if(!error){
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
/*Bundle b = new Bundle();
b.putString("status", "done");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK,intent);
finish();*/
}
}
});
mCancel.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Canceled");
/*Bundle b = new Bundle();
b.putString("status", "cancel");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK,intent);
finish();*/
}
});
return viewFrag;
}
/* @Override
protected void onDestroy() {
Log.w("GetSignature", "onDestory");
super.onDestroy();
}*/
private boolean captureSignature() {
boolean error = false;
String errorMessage = "";
if(yourName.getText().toString().equalsIgnoreCase("")){
errorMessage = errorMessage + "Please enter your Name\n";
error = true;
}
if(error){
Toast toast = Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 105, 50);
toast.show();
}
return error;
}
private String getTodaysDate() {
final Calendar c = Calendar.getInstance();
int todaysDate = (c.get(Calendar.YEAR) * 10000) +
((c.get(Calendar.MONTH) + 1) * 100) +
(c.get(Calendar.DAY_OF_MONTH));
Log.w("DATE:",String.valueOf(todaysDate));
return(String.valueOf(todaysDate));
}
private String getCurrentTime() {
final Calendar c = Calendar.getInstance();
int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000) +
(c.get(Calendar.MINUTE) * 100) +
(c.get(Calendar.SECOND));
Log.w("TIME:",String.valueOf(currentTime));
return(String.valueOf(currentTime));
}
private boolean prepareDirectory()
{
try
{
if (makedirs())
{
return true;
} else {
return false;
}
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(context, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
return false;
}
}
private boolean makedirs()
{
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory())
{
File[] files = tempdir.listFiles();
for (File file : files)
{
if (!file.delete())
{
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}
public class signature extends View
{
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
Context context;
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs)
{
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void save(View v)
{
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
}
Canvas canvas = new Canvas(mBitmap);
try
{
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = Images.Media.insertImage(context.getContentResolver(), mBitmap, "title", null);
Log.v("log_tag","url: " + url);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 90,baos);
byte[] byteData=baos.toByteArray();
db.open();
db.storeImage(byteData);
//In case you want to delete the file
//boolean deleted = mypath.delete();
//Log.v("log_tag","deleted: " + mypath.toString() + deleted);
//If you want to convert the image to string use base64 converter
}
catch(Exception e)
{
Log.v("log_tag", e.toString());
}
}
public void clear()
{
path.reset();
invalidate();
}
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++)
{
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void debug(String string){
}
private void expandDirtyRect(float historicalX, float historicalY)
{
if (historicalX < dirtyRect.left)
{
dirtyRect.left = historicalX;
}
else if (historicalX > dirtyRect.right)
{
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top)
{
dirtyRect.top = historicalY;
}
else if (historicalY > dirtyRect.bottom)
{
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY)
{
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
如何将图像发送到数据库?