No error when updating, but the image cannot updated android sqlite - android

So I have an SQLite database. I try to update and there is no error in my android application. When I update only the name or the cost, it successfully updated but the image not showing in my gridview. But when I Update only the image, it is successfully updated.Can someone please help me out here!
this my Database Class:
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydaringdb";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_PRODUK = "produk";
public static final String KEY_ID_PRODUK = "id";
public static final String KEY_NAMA_PRODUK = "nama_produk";
public static final String KEY_HARGA_PRODUK = "harga_produk";
public static final String KEY_GAMBAR_PRODUK = "gambar_produk";
//for showing 1 product
public ModelProduk getnama(int selection) {
SQLiteDatabase db = this.getReadableDatabase();
String cb = "SELECT * FROM " + TABLE_PRODUK + " WHERE " + KEY_ID_PRODUK + "= '" + selection + "'";
Cursor cursor = db.rawQuery(cb, null);
if (cursor != null)
cursor.moveToFirst();
ModelProduk modelProduk = new ModelProduk();
modelProduk.set_id(Integer.parseInt(cursor.getString(0)));
modelProduk.set_nama(cursor.getString(1));
modelProduk.set_harga(Integer.parseInt(cursor.getString(2)));
modelProduk.set_gambar(cursor.getBlob(3));
return modelProduk;
}
//for update 1 product
public void update(ModelProduk modelProduk) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
// update baris
db.update(TABLE_PRODUK, values, where, whereArgs);
}
My update class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_produk);
init();
tambahgambaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
simpandatau.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
modelProduk.set_nama(deskripsiu.getText().toString());
modelProduk.set_harga(Integer.parseInt(harga_produku.getText().toString()));
modelProduk.set_gambar(getImageByte(bitmap));
db.update(modelProduk);
Toast.makeText(getApplicationContext(), "Data Berhasil Diubah!", Toast.LENGTH_SHORT).show();
}
});
kembaliu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UpdateProduk.this, Produk.class);
startActivity(i);
finish();
}
});
}
public void refresh(){
produklist = new ArrayList<>();
adapter = new ProdukAdapter( this, produklist);
produklist.clear();
produklist.addAll(db.getAllProduk());
adapter.notifyDataSetChanged();
}
private void init(){
pilih = getIntent().getIntExtra("id_produk", 0);
db = new Database(this);
modelProduk = db.getnama(pilih);
gambar_produku = (ImageView) findViewById(R.id.pilihgambaru);
tambahgambaru = (Button) findViewById(R.id.btaddu);
simpandatau = (Button) findViewById(R.id.btsimpanu);
deskripsiu = (EditText) findViewById(R.id.etdesku);
harga_produku = (EditText) findViewById(R.id.ethargau);
kembaliu = (Button) findViewById(R.id.btkembaliu);
deskripsiu.setText(modelProduk.get_nama());
harga_produku.setText(String.valueOf(modelProduk.get_harga()));
gambar_produku.setImageBitmap(bitmap(modelProduk.get_gambar()));
}
public void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Pilih Gambar"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode==RESULT_OK) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
gambar_produku.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getImageByte(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[]=null;
if(bitmap!=null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
imageInByte=stream.toByteArray();
}
return imageInByte;
}
public Bitmap bitmap (byte[] byteImage){
byte[] outImage = byteImage;
Bitmap image ;
if (outImage != null){
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
image = BitmapFactory.decodeStream(imageStream);
}else {
image= null;
}
return image;
}
}
my update.xml:
<ImageView
android:id="#+id/pilihgambaru"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#mipmap/ic_launcher"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/btaddu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/pilihgambaru"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="pilih gambar"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="#+id/etdesku"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:layout_below="#id/btaddu"
android:layout_centerHorizontal="true"
android:hint="Masukkan Deskripsi Barang"
android:inputType="textMultiLine"
android:maxLength="100"
/>
<EditText
android:id="#+id/ethargau"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#id/etdesku"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:hint="Masukkan Harga Barang"
android:inputType="number"
android:maxLength="10"
/>
<Button
android:id="#+id/btsimpanu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ethargau"
android:layout_marginTop="10dp"
android:text="simpan"
android:layout_marginLeft="100dp"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/btkembaliu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btsimpanu"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="ke produk"
/>

Related

android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)

Hello I am getting this strange error in my app. The first time the application starts it runs however when I store a photo from the camera the app crashes and shows this log. The app takes photo from the camera or gallery and saves them in the database and displays the photo in a custom gridview.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notepad.isidorosioannou.notepad/com.example.notepad.isidorosioannou.notepad.CameraMainActivity}: android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2444)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.access$900(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Caused by: android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)
at android.database.CursorWindow.nativeGetBlob(Native Method)
at android.database.CursorWindow.getBlob(CursorWindow.java:403)
at android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:45)
at com.example.notepad.isidorosioannou.notepad.DatabaseAdapt.cursorToImage(DatabaseAdapt.java:179)
at com.example.notepad.isidorosioannou.notepad.DatabaseAdapt.loadAllImages(DatabaseAdapt.java:162)
at com.example.notepad.isidorosioannou.notepad.CameraMainActivity.onCreate(CameraMainActivity.java:48)
Here is part of the code from my db Helper and actually the methods that i get the error in the log.
public static final String CAMERANOTE_CREATE = "create table " + CAMERANOTE_TABLE + " ( "
+ CAMERA_ID + " integer primary key autoincrement, "
+ CAMERA_TITLE + " text not null, "
+ CAMERA_DESC + " text not null, "
+ CAMERA_PATH + " blob);";
public long createCamera(DataImage image){
ContentValues contentValues = new ContentValues();
contentValues.put(CAMERA_TITLE,image.getTitle());
contentValues.put(CAMERA_DESC,image.getDesc());
contentValues.put(CAMERA_PATH,image.getPath());
long insert= sqlDB.insert(CAMERANOTE_TABLE,null,contentValues);
return insert;
public ArrayList<DataImage> loadAllImages(){
ArrayList<DataImage> imageList= new ArrayList<>();
Cursor cursor = sqlDB.query(CAMERANOTE_TABLE,new String[]{CAMERA_ID,CAMERA_TITLE,CAMERA_DESC,CAMERA_PATH},null,null,null,null,null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
DataImage image = cursorToImage(cursor);
imageList.add(image);
}
cursor.close();
return imageList;
}
public Cursor loadAllTasks (){
Cursor cursor = sqlDB.query(TODOLIST_TABLE,new String[]{TODO_ID,TODO_TEXT,TODO_CHECKED},null,null,null,null,null);
return cursor;
}
private DataImage cursorToImage(Cursor cursor){
int id = cursor.getInt(cursor.getColumnIndex(DatabaseAdapt.CAMERA_ID));
String text = cursor.getString(cursor.getColumnIndex(DatabaseAdapt.CAMERA_TITLE));
String desc = cursor.getString(cursor.getColumnIndex(DatabaseAdapt.CAMERA_DESC));
byte [] path = cursor.getBlob(cursor.getColumnIndex(DatabaseAdapt.CAMERA_PATH));
DataImage image= new DataImage(id,text,desc,path);
return image;
}
}
Here is my main activity:
public class CameraMainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView buttonImage;
private GridView gridView;
private ArrayList<DataImage> imageList;
public DatabaseAdapt dbAdapter;
private CameraAdapter cameraAdapter;
private AlertDialog alertBuilder;
private Uri imageUri;
private Bitmap bitMap;
private byte [] byteArray;
private static final int REQUEST_CAMERA_CODE = 1;
private static final int REQUEST_GALLERY_CODE=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar3);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
buttonImage = (ImageView)findViewById(R.id.cameraOptionButton);
buttonImage.setOnClickListener(this);
gridView = (GridView) findViewById(R.id.gridviewPhoto);
dbAdapter = new DatabaseAdapt(getApplicationContext());
dbAdapter.open();
imageList = new ArrayList<>();
imageList = dbAdapter.loadAllImages();
cameraAdapter = new CameraAdapter(this,imageList);
gridView.setAdapter(cameraAdapter);
createAlertWindow();
}
public void onDestroy(){
super.onDestroy();
dbAdapter.close();
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.cameraOptionButton){
alertBuilder.show();
}
}
private void createAlertWindow(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_title)
.setItems(R.array.alert_dialog, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
activateCamera();
}
else{
chooseFromGallery();
}
}
});
alertBuilder = alertDialog.create();
}
private void activateCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,REQUEST_CAMERA_CODE);
}
private void chooseFromGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUEST_GALLERY_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data !=null){
Bundle extra = data.getExtras();
bitMap = extra.getParcelable("data");
byteArray = convertToByte(bitMap);
}
else if(requestCode==REQUEST_GALLERY_CODE && resultCode == RESULT_OK && data !=null){
imageUri = data.getData();
bitMap = decodeUri(imageUri,400);
byteArray=convertToByte(bitMap);
}
Intent intent = new Intent(this,CameraSaveActivity.class);
intent.putExtra("byteImage",byteArray);
startActivity(intent);
}
private Bitmap decodeUri(Uri image,int size){
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(image),null,options);
int width = options.outWidth;
int height = options.outHeight;
int scale = 1;
while (true){
if(width/2<size || height/2<size){
break;
}
width /=2;
height /=2;
scale *=2;
}
BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize=scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(image),null,options2);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private byte[] convertToByte(Bitmap bitmap){
ByteArrayOutputStream b = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,b );
return b.toByteArray();
}
}
and here is my second activity where I just preview the image and save it.
public class CameraSaveActivity extends AppCompatActivity implements View.OnClickListener {
private EditText cameraSaveTitle , cameraSaveDesc;
private ImageView cameraPreview;
private Button saveButton;
private byte [] byteArray;
private DatabaseAdapt adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_save);
cameraSaveTitle = (EditText)findViewById(R.id.cameraEditTitle);
cameraSaveDesc = (EditText)findViewById(R.id.cameraEditDesc);
cameraPreview = (ImageView)findViewById(R.id.cameraPreview);
saveButton = (Button)findViewById(R.id.saveCameraButton);
Intent intent = getIntent();
byteArray = intent.getByteArrayExtra("byteImage");
ByteArrayInputStream imageStream = new ByteArrayInputStream(byteArray);
cameraPreview.setImageBitmap(BitmapFactory.decodeStream(imageStream));
adapt = new DatabaseAdapt(this);
adapt.open();
saveButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.saveCameraButton){
String text1 = cameraSaveTitle.getText().toString();
String text2 = cameraSaveDesc.getText().toString();
DataImage image = new DataImage(text1,text2,byteArray);
adapt.createCamera(image);
finish();
}
}
public void onDestroy(){
super.onDestroy();
adapt.close();
}
}
Can someone please help. I searched but I could not find a solution
Your problem is that you are storing path in CAMERA_PATH, which is string and trying to get a Blob. There is a type mismatch and thats why the error is thrown.
You need to insert a blob in the CAMERA_PATH before you try retrieving a blob from there.

Take Picture From Camera And Show it to the ImageView Android

before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview

Android while using cardview image is loading very lazy

I am loading pictures (below ~3MB in size) into Cardview from a database and it was infalte in Listviewstview.
The loading and browsing of these pictures is way too slow.
Is there any method to downscale these pictures to speed up & sometimes dispalyind [Duplicate] images on other card view?
cardview xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="140dp"
android:alpha="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
card_view:cardBackgroundColor="#FFFFFF"
card_view:cardCornerRadius="10dp">
<RelativeLayout
android:id="#+id/r1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img_product"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginLeft="#dimen/activity_vertical_margin"
android:layout_marginTop="20dp" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:inputType="textMultiLine"
android:text="Parvana Fancy Necklace Set"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:text="RS.234"
android:textSize="20dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_remove"
android:layout_width="32dp"
android:layout_height="wrap_content"
android:background="#drawable/wishlistddelete_selector"
android:drawableLeft="#drawable/delete_icon"
android:layout_alignTop="#+id/txt_total"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
listview xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/home_bground">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/topbar1"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#drawable/top">
<ImageView
android:id="#+id/btn_hme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:src="#drawable/home_icon" />
<TextView
android:id="#+id/txt_pro_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center_horizontal"
android:text="Shopping Cart"
android:textColor="#ffffff"
android:textSize="18dp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/topbar1"
android:animationCache="false"
android:dividerHeight="0dp"
android:listSelector="#00000000"
android:scrollingCache="false"
android:smoothScrollbar="true" />
</RelativeLayout>
</RelativeLayout>
by using sqllite access the data from database
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
private Context context;
Integer i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
ListCart.setScrollingCacheEnabled(false);
Intent page2 = getIntent();
i = page2.getIntExtra("kvalue",1);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
String s1 = ProductPrice.toString();
}
}
adapter class
public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Try scale your bitmap to lower its actual resolution, I've used the following codes to reduce bitmap's size.
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
For you case, add the following codes into your adapter class AsyncTask's doInBackground method
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
} catch (Exception e) {
e.printStackTrace();
}
return scaled;
Return scaled bitmap instead of original bitmap.

How to dynamically add suggestions to autocompletetextview with preserving character status along with images

Currently I am using code to give text suggestion. I would like to add another text and image. How do I do that? Currently, I am using the code below.I shows text but image is not displayed .How do I set the image ?
public class AutoCompleteTextViewActivity extends Activity{
ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
// String a=constraint;
JSONObject json=JSONfunctions.getJSONfromURL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+ constraint +"&api_key=63692beaaf8ba794a541bca291234cd3&format=json");
JSONObject js1=json.getJSONObject("artist");
JSONObject js=js1.getJSONObject("similar");
JSONArray resultArray = js.getJSONArray("artist");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
String data = resultArray.getJSONObject(i).getString("name");
String dataimage = resultArray.getJSONObject(i).getJSONArray("image").getJSONObject(i).getString("#text");
cursor.newRow().add(i)
.add(data)
.add(data)
.add(data);
String link = dataimage;
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
public void run() {
String TAG="log";
// TODO do real network request
// simulate network delay
// Log.d(TAG, "getting " + mUrl);
// try {
// Thread.sleep(2000 + (long) (4000 * Math.random()));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Bitmap b = imageLoader.loadImageSync(mUrl.toString());
// Bitmap b = BitmapFactory.decodeResource(getResources(), mUrl.toString());
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
}
}
///////////////
MyMatrixCursor
//////////
public class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}
////////
JSONfunctions
///////
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.w("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.w("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
////////
main.xml
///
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Artist"
android:textAppearance="?android:attr/textAppearanceLarge" />
<AutoCompleteTextView
android:id="#+id/actv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"> <requestFocus />
</AutoCompleteTextView>
<TextView
android:id="#+id/selection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
/////
list_row.xml
///
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:src="#drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"/>
</LinearLayout>
<!-- Title Of Song-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- Artist Name -->
<!-- Rightend Duration -->
<!-- Rightend Arrow -->
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_centerVertical="true"
android:text="test"
android:textColor="#040404"
android:textSize="5dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
</RelativeLayout>
///
Manifest
///
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".AutoCompleteTextViewActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ok try this:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
String[] from = {"name"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to) {
// required for Spanned data
#Override
public void bindView(View view, Context context, Cursor cursor) {
MyCursor c = (MyCursor) cursor;
TextView tv = (TextView) view;
tv.setText(c.getSpanned());
}
// required for Spanned data
#Override
public CharSequence convertToString(Cursor cursor) {
MyCursor c = (MyCursor) cursor;
return c.getSpanned();
}
};
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
MyCursor c = new MyCursor();
// fake web service responses
List<String> names = callFakeWebService(constraint);
int i = 0;
for (String name: names) {
SpannableStringBuilder ssb = new SpannableStringBuilder(name);
int start = name.indexOf(" ");
ForegroundColorSpan what = new ForegroundColorSpan(0xffff0000);
ssb.setSpan(what, start + 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
c.newRow().add(i++).add(name);
c.addSpanned(ssb);
}
return c;
}
// fake web service request
private List<String> callFakeWebService(CharSequence constraint) {
Log.d(TAG, "callFakeWebService for: " + constraint);
String[] namesArr = {
"Mark Smith",
"Monica Thompson",
"John White",
"Jane Brown"
};
String stringConstraint = constraint.toString().toLowerCase();
List<String> names = new ArrayList<String>();
for (int i = 0; i < namesArr.length; i++) {
String name = namesArr[i];
if (name.toLowerCase().startsWith(stringConstraint)) {
names.add(name);
}
}
return names;
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
ll.addView(actv);
TextView tv = new TextView(this);
tv.setTextSize(32);
tv.setTextColor(0xffff0000);
tv.setText("type one of:\n mark,\n monica,\n john\n jane");
ll.addView(tv);
setContentView(ll);
where custom Cursor could look like this (it is minimalistic version supporting only one Spanned in a row):
static class MyCursor extends MatrixCursor {
private static final String[] NAMES = {BaseColumns._ID, "name"};
private ArrayList<Spanned> mSpannedList;
public MyCursor() {
super(NAMES);
mSpannedList = new ArrayList<Spanned>();
}
public void addSpanned(Spanned s) {
mSpannedList.add(s);
}
public Spanned getSpanned() {
return mSpannedList.get(mPos);
}
}
EDIT with no Spanned text:
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
String jsonStr = "{\"ResultArray\":[{\"data\":{ \"sno\":\"sno1\", \"date\":\"2011-08-21 14:27:09\", \"user\":\"1\", \"link\":\"http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg?t=20111117074048\", \"name\":\"Aa\" }},{\"data\":{ \"sno\":\"sno2\", \"date\":\"2011-08-21 14:28:09\", \"user\":\"2\", \"link\":\"http://kcclaveria.com/wp-content/uploads/2013/02/google-panda-penguin.jpg\", \"name\":\"Bb\" }}]}";
JSONObject json = new JSONObject(jsonStr);
JSONArray resultArray = json.getJSONArray("ResultArray");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
JSONObject data = resultArray.getJSONObject(i).getJSONObject("data");
cursor.newRow().add(i)
.add(data.getString("name"))
.add(data.getString("user"))
.add(data.getString("sno"));
String link = data.getString("link");
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
#Override
public void run() {
// TODO do real network request
// simulate network delay
Log.d(TAG, "getting " + mUrl);
try {
Thread.sleep(2000 + (long) (4000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
and the custom MatrixCursor:
class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}

Android code to record a video using remote IP camera which is accessed by using a url

Here are some links which tell about video recording:
How can I capture a video recording on Android?
https://github.com/churnlabs/android-ffmpeg-sample
and there are also many links which tell about video recording but got no any clue how to use the remote IP camera to record video.
By using different samples on stackoverflow I become able to take picture and save on sdcard but couldn't record video.
If any one has any idea or code along with required files I will be thankful.
For example the url I am using where the IP camera is available is given below:
http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=800x600&amp%3bdummy=1333689998337
Here is the layout code:
<RelativeLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/logo"
android:layout_alignParentTop="true"
android:layout_weight="1" >
<ImageButton
android:id="#+id/btnCam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
<ImageButton
android:id="#+id/btnVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
</RelativeLayout>
<LinearLayout
android:id="#+id/LinearLayout03"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/LinearLayout01"
android:layout_below="#+id/LinearLayout02"
android:layout_weight="1" >
<RelativeLayout
android:id="#+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#ffffff" >
<view
android:id="#+id/mv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
class="com.apps.GrahamConst.MjpegView" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:background="#drawable/navbar" >
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/previous" >
</ImageButton>
<ImageButton
android:id="#+id/btnMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/main" >
</ImageButton>
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/next" >
</ImageButton>
</LinearLayout>
</RelativeLayout>
Here is my Activity
public class CameraDetails2 extends Activity implements OnClickListener {
private MediaScannerConnection m_pScanner;
String drawable = null;
private MjpegView mv;
private ProgressDialog dialog;
private HashMap<String, String> item;
private int id = -1;
private WindowManager winMan;
boolean recording = false;
MediaRecorder recorder;
int bytearraysize = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
winMan = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
if (winMan != null) {
int orientation = winMan.getDefaultDisplay().getOrientation();
if (orientation == 0) {
// Portrait
setContentView(R.layout.cameradetails);
} else if (orientation == 1) {
// Landscape
setContentView(R.layout.cameradetailsl);
}
}
Bundle b = getIntent().getExtras();
ImageButton b1 = (ImageButton) findViewById(R.id.btnNext);
b1.setOnClickListener(this);
ImageButton b2 = (ImageButton) findViewById(R.id.btnMain);
b2.setOnClickListener(this);
ImageButton b3 = (ImageButton) findViewById(R.id.btnPrevious);
b3.setOnClickListener(this);
ImageButton b4 = (ImageButton) findViewById(R.id.btnCam);
b4.setOnClickListener(this);
ImageButton b5 = (ImageButton) findViewById(R.id.btnVideo);
b5.setOnClickListener(this);
id = Integer.valueOf(b.get("id").toString());
item = listarrayadapter.cameraList.get(Integer.valueOf(id));
mv = (MjpegView) findViewById(R.id.mv);
try {
getVal(item.get("cameraLink"));
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&amp%3bdummy=1333689998337");
} catch (Exception e) {
e.printStackTrace();
mv.setBackgroundResource(R.drawable.offline);
}
}
#Override
protected void onResume() {
// if(recording)
// {
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&amp%3bdummy=1333689998337");
// }
super.onResume();
}
public void onPause() {
super.onPause();
dialog.dismiss();
mv.stopPlayback();
}
private void getVal(final String url) {
Log.i("URL===", url);
updateButtons();
dialog = ProgressDialog.show(this, null, null, true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = null;
checkUpdate = new Thread() {
public void run() {
mv.setSource(MjpegInputStream.read(url));
mv.setDisplayMode(MjpegView.SIZE_FULLSCREEN);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int btn = v.getId();
if (btn == R.id.btnMain) {
Intent intent = new Intent();
intent.setClass(CameraDetails2.this, CamerasList.class);
startActivity(intent);
finish();
}
if (btn == R.id.btnNext) {
id += 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnPrevious) {
id -= 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnCam) {
if (mv != null) {
Date dt = new Date();
int years = dt.getYear();
int month = dt.getMonth();
int day = dt.getDay();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
final String filename = years + "" + month + "" + day + ""
+ hours + "" + minutes + "" + seconds;
try {
Bitmap image = MjpegView.savebmp;
File SDCardRoot =
Environment.getExternalStorageDirectory();
FileOutputStream fileOutputStream = null;
fileOutputStream = new FileOutputStream(
SDCardRoot.toString() + "/" +
filename + ".jpg");
BufferedOutputStream bos = new
BufferedOutputStream(
fileOutputStream);
int quality = 95;
image.compress(CompressFormat.JPEG, quality, bos);
final String szFile = SDCardRoot.toString() + "/"
+ filename + ".jpg";
m_pScanner = new MediaScannerConnection(this,
new MediaScannerConnectionClient()
{
public void
onMediaScannerConnected() {
m_pScanner
.scanFile(szFile, null /* mimeType */);
}
public void
onScanCompleted(String path, Uri uri) {
if
(path.equals(szFile)) {
CameraDetails2.this
.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
"Image Saved.",
Toast.LENGTH_LONG)
.show();
}
});
m_pScanner.disconnect();
}
}
});
m_pScanner.connect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (btn == R.id.btnVideo) {
if (recording) {
// stop and save
recording = false;
MjpegInputStream.isrecording = false;
List<byte[]> bytelist = new ArrayList<byte[]>();
ArrayList<ByteArrayOutputStream> byteArrayStream =
MjpegInputStream.byteArrayStream;
for (int i = 0; i < byteArrayStream.size(); i++) {
byte[] templist
=byteArrayStream.get(i).toByteArray();
bytelist.add(templist);
}
for (int j = 0; j < bytelist.size(); j++) {
bytearraysize += bytelist.get(j).length;
}
byte[] totalbytes = new byte[bytearraysize];
int f = 0;
for (int j = 0; j < bytelist.size(); j++) {
for (int a = 0; a < bytelist.get(j).length; a++) {
totalbytes[f] = bytelist.get(j)[a];
f++;
}
}
Log.e("num of bytes", "" + totalbytes.length);
// Byte[] bytes = bytelist.toArray(new
//Byte[bytelist.size()]);
try {
writeToFile(totalbytes, "" +
System.currentTimeMillis());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
recording = true;
MjpegInputStream.isrecording = true;
// onResume();
// start recording
}
// recorder=new MediaRecorder();
// try {
// recorder.prepare();
// } catch (IllegalStateException e) {
// e.printStackTrace();
// finish();
// } catch (IOException e) {
// e.printStackTrace();
// finish();
// }
//
// //recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
// // recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
//
// //
// //
// // CamcorderProfile cpHigh = CamcorderProfile
// // .get(CamcorderProfile.QUALITY_HIGH);
// // recorder.setProfile(cpHigh);
// recorder.setVideoSource(mv.getId());
// recorder.setOutputFile("/sdcard/videocapture_example.mp4");
// recorder.setMaxDuration(50000); // 50 seconds
// recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
}
public void writeToFile(byte[] bytes, String videoname) throws IOException {
try {
Log.e("num of bytes to be saved", "" + bytes.length);
String path = "/sdcard/" + videoname + ".mp4";
FileOutputStream stream = new FileOutputStream(path);
stream.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void updateButtons() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
ImageButton btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
if (id == 0) {
btnPrevious.setEnabled(false);
} else {
btnPrevious.setEnabled(true);
}
if (id == listarrayadapter.cameraList.size() - 1) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
}
}

Categories

Resources