how to change default file path - android

my code is save images from gallery in default location /data/data/applicationname/files
if i change path in AppPhotos class to "/data/data/com.isummation.customgallery/files/";
this is not show any image in list what do ido?? plz help me
public class AndroidCustomGalleryActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
Cursor imagecursor;
int image_column_index;
Button selectBtn;
ProgressDialog myProgressDialog = null;
DataBase db;
Handler handle = new Handler(){
public void handleMessage(Android.os.Message message) {
if (message.what == 1)
{
hideProgress();
GridView imagegrid = (GridView)
findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
}
else if (message.what == 3)
{
hideProgress();
AndroidCustomGalleryActivity.this.finish();
}
else if (message.what == 2)
{
hideProgress();
}
super.handleMessage(msg);
};
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showProgress();
new Thread() {
public void run() {
try
{
SelecedtPhotos();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 3;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
});
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem,
null);
holder.imageview = (ImageView)
convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox)
convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id])
{
cb.setChecked(false);
thumbnailsselection[id] = false;
}
else
{
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
/*holder.imageview.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" +
arrPath[id]), "image/*");
startActivity(intent);
}
});*/
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
public void loadFeed()
{
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, null,null, orderBy);
image_column_index =
imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++)
{
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex =
imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] =
MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext()
.getContentResolver(), id,MediaStore.Images.Thumbnails.MICRO_KI ND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
imagecursor.close();
}
private void showProgress()
{
myProgressDialog =
ProgressDialog.show(AndroidCustomGalleryActivity.this,null, "Loading
Data...", true);
}
private void hideProgress()
{
if (myProgressDialog != null)
myProgressDialog.dismiss();
}
///////////////////// Get File Name from path ////////////////////////////
public String FileName(String path)
{
String f = " /";
boolean c = false;
for(int i=path.length()-1;i>0;i--)
{
if(c == false)
if(path.charAt(i) == f.charAt(1))
{
c = true;
return
path.substring(i+1,path.length());
}
}
return "";
}
///////////////////// Get Extension from path ////////////////////////////
public String fileExt(String audio)
{
String fileName = "";
String f = " .";
boolean c = false;
for(int I=audio.length()-1;I>0;I--)
{
if(c == false)
if(audio.charAt(I) == f.charAt(1))
{
fileName = audio.substring(I+1, audio.length());
c = true;
}
}
return fileName;
}
public void SelecedtPhotos()
{
final int len = thumbnailsselection.length;
// int cnt = 0;
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
//cnt++;
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(arrPath[i],
options);
try {
FileOutputStream outputStream =
openFileOutput(FileName(arrPath[i]), Context.MODE_PRIVATE);
outputStream.write(getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
db.insert_update("INSERT INTO Photos(name,ext,path)
VALUES ('"+FileName(arrPath[i])+"','"+fileExt(arrPath[i])+"','"+arrPath[i]+"')");
db.close();
File file = new File(arrPath[i]);
boolean t = file.delete();
}
}
}
}
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.database.DataBase;
import com.isummation.customgallery.R;
public class AppPhotos extends Activity{
ProgressDialog myProgressDialog = null;
ListView list;
Activity activity = AppPhotos.this;
List<AppPhotosData> picList;
DataBase db;
int position;
Handler handle = new Handler(){
public void handleMessage(Android.os.Message message) {
if (message.what == 1)
{
hideProgress();
list.setAdapter(new
AppPhotosAdapter(getApplicationContext(),activity,0,picList));
}
else if (message.what == 2)
{
hideProgress();
}
super.handleMessage(msg);
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photolist);
list = (ListView) findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
position = arg2;
AlertDialog.Builder builder = new
AlertDialog.Builder(AppPhotos.this);
builder.setTitle("Hidden Photos");
builder.setMessage("Are you sure you want to revert the
photo?");
builder.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
DialogBtn();
}
});
builder.setNegativeButton("No", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
private void showProgress()
{
myProgressDialog = ProgressDialog.show(AppPhotos.this,null, "Loading...",
true);
}
private void hideProgress()
{
if (myProgressDialog != null)
myProgressDialog.dismiss();
}
public void loadFeed()
{
String filePaths = "/data/data/com.isummation.customgallery/files/";
File outputFile1 = new File(filePaths);
File[] files1 = outputFile1.listFiles();
picList = new ArrayList<AppPhotosData>();
for(File f:files1)
{
AppPhotosData picObj = new AppPhotosData();
Bitmap bmDulicated4 = BitmapFactory.decodeFile(f.getAbsolutePath());;
picObj.setImage(bmDulicated4);
picObj.setName(f.getName());
picList.add(picObj);
}
}
public void DialogBtn()
{
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
Cursor DataC = db.selectQuery("SELECT path FROM Photos where name
='"+picList.get(position).getName()+"'");
if(DataC.getCount() > 0)
{
Bitmap bitmap = picList.get(position).getImage();
if(picList.get(position).getImage() != null)
{
try {
FileOutputStream outputStream = new
FileOutputStream(DataC.getString(DataC.getColumnIndex("path")));
outputStream.write(getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File("/data/data/com.isummation.customgallery
/files/"+picList.get(position).getName());
file.delete();
showProgress();
new Thread() {
public void run() {
try
{
loadFeed();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
catch(Exception e)
{
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}
}
}.start();
}
}
db.close();
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
}

Manually create your app directory in sd card and then save image in that directory.
You can try following snippet.
String root=Environment.getExternalStorageDirectory().toString();
File myDir = new File(root+"/demo_image");
if(!myDir.exists())
{
myDir.mkdir();
}
String fname = "Image"+String.valueOf(System.currentTimeMillis())+".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.JPEG,100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

android JSON upload images collection dose not work

I'm trying to upload some of images after selecting it from my UploadActivity.
public static int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
private static final int PICK_FROM_CAMERA = 1;
ArrayList<String> IPath = new ArrayList<String>();
public static Uri uri;
TextView msgLoading;
//ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
msgLoading = (TextView) findViewById(R.id.msgLoading);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
final Cursor imagecursor = getImageCursor();
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
msgLoading.setVisibility(View.GONE);
}
},100);
final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
uploadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i = 0; i < len; i++) {
if (thumbnailsselection[i]) {
cnt++;
selectImages = arrPath[i];
IPath.add(selectImages);
}
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt + " image(s).",
Toast.LENGTH_LONG).show();
Log.i("SelectedImages", String.valueOf(selectImages.toCharArray()));
Intent intentMessage = new Intent(UploadActivity.this,
ImagesForAds.class);
intentMessage.putStringArrayListExtra("IMAGE", IPath);
startActivity(intentMessage);
}
}
});
}
#NonNull
private Cursor getImageCursor() {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
final Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
final int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
return imagecursor;
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]) {
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
"image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent i = new Intent(UploadActivity.this, ImagesForAds.class);
UploadActivity.this.finish();
startActivity(i);
super.onBackPressed();
}
and it's worked fine, I can back data to my main activity as below :
b = getIntent().getExtras();
if (b != null) {
ImgData = b.getStringArrayList("IMAGE");
for (int i = 0; i < ImgData.size(); i++) {
map.add(ImgData.get(i).toString());
}
}
now it's ok... I need to upload those Images that I selected, here is my asyncTask:
public class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ImagesForAds.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url = "myLink";
int i = Integer.parseInt(params[0]);
Bitmap bitmap = decodeFile(map.get(i));
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
//entity.addPart("user_id", new StringBody("199"));
//entity.addPart("club_id", new StringBody("10"));
entity.addPart("images", new ByteArrayBody(data,
"image/jpeg", params[1]));
Log.i(TAG, "array map: " + map.get(i));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
count++;
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
and here how I invoke it :
int count = 0;
new ImageUploadTask().execute(count + "", "pk" + count + ".jpg");
The issue with AsyncTask.. it's upload only 1 image, how I can upload all images I have selected ?
This is your flaw :
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
not a good idea to create a new ImageUploadTask inside ImageUploadTask.
move your for loop inside doInBackground() and for updating user use publishProgress() and catch that event inside onProgressUpdate.
Read more about AsyncTask : https://developer.android.com/reference/android/os/AsyncTask.html

Get the item index of a listview and delete it on the listview and on my database

I'm now currently working on a project that lets the user view the list of a certain table and has the privilege of either editing or deleting it. There's no error, I just don't have any idea on what to do. Maybe anyone could help me on even just the delete feature? Giving a sample code would be so much helpful. Here's my code:
SQLiteDatabase myDataBase;
String DB_PATH = null;
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
int totalId, totalProdId, totalQty, totalBigQty, totalUnitQty;
Cursor cursorProduct;
String id = "";
String productid = "";
String qty = "";
String bigqty = "";
String unitqty = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dc_invviewlist);
copyDB();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH,null);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.dc_inventory_viewlist, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DC_invviewlist.this,
"Please wait...", "Retrieving data ...", true);
registerForContextMenu(getListView());
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
String i = getPIViewListId();
String pi = getPIViewListProdId();
String q = getPIViewListQty();
String bq = getPIViewListBigQty();
String uq = getPIViewListUnitQty();
String[] iValue = i.split("~");
String[] piValue = pi.split("~");
String[] qValue = q.split("~");
String[] bqValue = bq.split("~");
String[] uqValue = uq.split("~");
totalId = iValue.length;
totalProdId = piValue.length;
totalQty = qValue.length;
totalBigQty = bqValue.length;
totalUnitQty = uqValue.length;
m_orders = new ArrayList<Order>();
for (int j = 0; j < totalId; j++) {
Order o = new Order();
o.setOrderId(iValue[j]);
o.setOrderProdId(piValue[j]);
o.setOrderQty(qValue[j]);
o.setOrderBigQty(bqValue[j]);
o.setOrderUnitQty(uqValue[j]);
m_orders.add(o);
}
Thread.sleep(2000);
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.dc_inventory_viewlist, null);
}
Order o = items.get(position);
if (o != null) {
TextView id = (TextView) v.findViewById(R.id.txtInvViewListId);
TextView prodid = (TextView) v.findViewById(R.id.txtInvViewListProductId);
TextView qty = (TextView) v.findViewById(R.id.txtInvViewListQty);
TextView bigqty = (TextView) v.findViewById(R.id.txtInvViewListBigQty);
TextView unitqty = (TextView) v.findViewById(R.id.txtInvViewListUnitQty);
if (id != null) {
id.setText(o.getOrderId()); }
if(prodid != null){
prodid.setText(o.getOrderProdId());
}
if(qty != null){
qty.setText(o.getOrderQty());
}
if(bigqty != null){
bigqty.setText(o.getOrderBigQty());
}
if(unitqty != null){
unitqty.setText(o.getOrderUnitQty());
}
}
return v;
}
}
public void copyDB(){
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationContext().getApplicationInfo().dataDir + "/databases/";
}
else{
DB_PATH = "/data/data/" + getApplicationContext().getPackageName() + "/databases/";
}
File dbdir = new File(DB_PATH);
if(!dbdir.exists()){
dbdir.mkdirs();
}
File file = new File(DB_PATH+"DC");
if(!file.exists()){
try{
InputStream is = getApplicationContext().getAssets().open("DC");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.flush();
fos.close();
}catch(Exception e){ throw new RuntimeException(e);};
}
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationInfo().dataDir + "/databases/DC";
}else{
DB_PATH = "/data/data/" + getPackageName() + "/databases/DC";
}
}
#Override
protected void onResume() {
super.onResume();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null);
}
#Override
protected void onPause() {
super.onPause();
myDataBase.close();
}
public String getPIViewListId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
id += ""+cursorProduct.getString(0)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return id;
}
public String getPIViewListProdId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
productid += ""+cursorProduct.getString(1)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return productid;
}
public String getPIViewListQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
qty += ""+cursorProduct.getString(2)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return qty;
}
public String getPIViewListBigQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
bigqty += ""+cursorProduct.getString(3)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return bigqty;
}
public String getPIViewListUnitQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
unitqty += ""+cursorProduct.getString(4)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return unitqty;
}
final int CONTEXT_MENU_EDIT_ITEM =1;
final int CONTEXT_MENU_DELETE =2;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_EDIT_ITEM, Menu.NONE, "Edit");
menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Long id = getListAdapter().getItemId(info.position);
switch (item.getItemId()) {
case CONTEXT_MENU_EDIT_ITEM:
//do smth
return(true);
case CONTEXT_MENU_DELETE:
myDataBase.execSQL("DELETE FROM tblProductInvAdjust");
return(true);
}
return(super.onOptionsItemSelected(item));
}
I hope anyone could help me on this. I really need a help right now. Thanks! :)
You can use this
sql_lite_db_obj.delete(tablename, whereClause, whereArgs)
For your convenience i edited my answer
public void clickHandler(View v) {
if (v.getId() == R.id.deleteOrder) {
int _id = 0;
try {
_id = (Integer) v.getTag(R.id.orderTitle);
} catch (Exception e) {
e.printStackTrace();
}
dh.delete(DatabaseHelpere.TableNAME, "_id=?",new String[] { String.valueOf(_id) });
}
}

adapter holder on listener cannot be final

I need to add a progress listener to each element of the horizontal list view, how can I do that?
For each item I upload a file.
I wanna to do something like that but holder is not final, so I have an error.
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResourceId;
List<Upload> listFileToUpload;
public UploadsViewAdapter(Context context, int layoutResourceId, List<Upload> data) {
this.mLayoutResourceId = layoutResourceId;
this.mContext = context;
this.listFileToUpload = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.progressUpdate = (ProgressBar) row.findViewById(R.id.progressUpdate);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
holder.progressUpdate.setProgress(item.getProgress());
}
});
holder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
Class Update.java
public class Upload {
public String path;
public String type;
private int mProgress = 0;
private ProgressListener mListener;
public Upload(String path, String type) {
this.path = path;
this.type = type;
}
public void setProgressListener(ProgressListener listener) {
mListener = listener;
}
public void setProgress(int progress) {
mProgress = progress;
if (mListener != null) {
mListener.onProgress(progress);
}
}
public int getProgress() {
return mProgress;
}
public Bitmap getThumbnail(int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (
(halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth
) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public interface ProgressListener {
public void onProgress(int progress);
}
}
Class which updates the file:
public class TheFormFragment extends Fragment {
private AmazonS3Client mS3Client = new AmazonS3Client(
new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY));
public static final int RESULT_PHOTO_DISK = 10;
public static final int RESULT_PHOTO_APN = 100;
public static final int RESULT_VIDEO_APN = 1000;
public static final String INTENT_PHOTO_APN_PATH = "INTENT_PHOTO_APN_PATH";
public static final String INTENT_VIDEO_APN_PATH = "INTENT_VIDEO_APN_PATH";
private List<Medias> mTheFormPictures;
private static Activity mActivity;
private static ArrayList<Upload> mQueue;
private KeyboardEventLinearLayout mLinearLayoutBackground;
private LinearLayout mLinearLayoutPublish;
private TextView mTextViewPublish;
private ImageView mImageViewPublish; // todo image du bouton
private EditText mEditTextText;
private TextView mTextViewTitle;
private CircularImageView mCircularImageViewAvatar;
private ImageButton mImageButtonClose;
private ImageButton mImageButtonCamera;
private ImageButton mImageButtonLibrary;
private Tag[] mTags = null;
private Range mAutocompleting;
private LinearLayout mAutocompleteContainer;
private HorizontalListView mUploadsList;
private UploadsViewAdapter mUploading;
/**Contains list of images, vidoe to update*/
private List<Upload> listFileToUpload;
private KeyboardEventLinearLayout.KeyboardListener mKeyboardListener = new KeyboardEventLinearLayout.KeyboardListener() {
#Override
public void onShow() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.GONE);
}
}
#Override
public void onHide() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.VISIBLE);
}
}
};
private class Range {
public int start;
public int end;
public String value;
public Range(int start, int end, String value) {
this.start = start;
this.end = end;
this.value = value;
}
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence text, int start, int oldCount, int newCount) {
String before = text.subSequence(0, start + newCount).toString();
Range range = findEditingTag(before);
autocompete(range);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
};
private OnClickListener mAutocompleteItemClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
Editable text = mEditTextText.getText();
CharSequence tag = ((TextView) view).getText();
text.replace(mAutocompleting.start, mAutocompleting.end, tag);
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_the_form, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTheFormPictures = new ArrayList<Medias>();
mQueue = new ArrayList<Upload>();
mS3Client.setRegion(Region.getRegion(Config.AWS_REGION));
mLinearLayoutBackground = (KeyboardEventLinearLayout) mActivity.findViewById(R.id.linearLayoutBackground);
mLinearLayoutPublish = (LinearLayout) mActivity.findViewById(R.id.linearLayoutPublish);
mTextViewPublish = (TextView) mActivity.findViewById(R.id.textViewPublish);
mTextViewTitle = (TextView) mActivity.findViewById(R.id.textViewTitle);
mImageViewPublish = (ImageView) mActivity.findViewById(R.id.imageViewPublish);
mCircularImageViewAvatar = (CircularImageView) mActivity.findViewById(R.id.circularImageViewAvatar);
mEditTextText = (EditText) mActivity.findViewById(R.id.editTextText);
mImageButtonClose = (ImageButton) mActivity.findViewById(R.id.imageButtonClose);
mImageButtonCamera = (ImageButton) mActivity.findViewById(R.id.imageButtonCamera);
mImageButtonLibrary = (ImageButton) mActivity.findViewById(R.id.imageButtonLibrary);
mAutocompleteContainer = (LinearLayout) mActivity.findViewById(R.id.autocompleteLayout);
mUploadsList = (HorizontalListView) mActivity.findViewById(R.id.uploadsList);
listFileToUpload =new ArrayList<Upload>();
mUploading = new UploadsViewAdapter(mActivity, R.layout.upload_item, listFileToUpload);
mUploadsList.setAdapter(mUploading);
mLinearLayoutBackground.setKeyboardListener(mKeyboardListener);
configure();
super.onActivityCreated(savedInstanceState);
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void configure() {
AQuery aq = new AQuery(mActivity);
ImageOptions options = new ImageOptions();
//options.round = 180;
options.fileCache = false;
options.memCache = true;
//options.animation = AQuery.FADE_IN;
User user = Preferences.getUser(mActivity);
if (user != null) {
mTextViewTitle.setText(user.getFirst_name() + " " + user.getLast_name());
if (user.getAvatar() != null && user.getAvatar().length() > 0) {
aq.id(mCircularImageViewAvatar).image(user.getAvatar(), options);
}
}
StatusConfigTheForm configTheForm = Preferences.getConfigTheForm(mActivity);
if (configTheForm != null) {
Log.i("theform config success");
Log.d("avatar: " + user.getAvatar() + " " + configTheForm.getBorderWidth());
if (configTheForm.getColors().getBackground().length == 3) {
mLinearLayoutBackground.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackground())));
}
if (configTheForm.getColors().getBackgrounPublishButton().length == 3) {
// mButtonPublish.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
// prepare
int roundRadius = 6;
// normal state
GradientDrawable background_normal = new GradientDrawable();
background_normal.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
background_normal.setCornerRadius(roundRadius);
// pressed state
GradientDrawable bacground_pressed = new GradientDrawable();
bacground_pressed.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton()).replace("#", "#CC"))); // opacity
bacground_pressed.setCornerRadius(roundRadius);
// states (normal and pressed)
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, bacground_pressed);
states.addState(new int[] {-android.R.attr.state_pressed}, background_normal);
if (Build.VERSION.SDK_INT >= 16) {
mLinearLayoutPublish.setBackground(states);
} else {
mLinearLayoutPublish.setBackgroundDrawable(states);
}
}
if (configTheForm.getColors().getBackgroundTextView().length == 3) {
mEditTextText.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgroundTextView())));
}
if (configTheForm.getColors().getBorderColorPicture().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getBorderColorPicture()));
}
// add color tag here
if (configTheForm.getColors().getColorTextPublish().length == 3) {
mTextViewPublish.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextPublish())));
}
if (configTheForm.getColors().getColorTextAttachment().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getColorTextAttachment()));
}
if (configTheForm.getColors().getColorTextUser().length == 3) {
mTextViewTitle.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextUser())));
}
if (configTheForm.getBorderWidth() > 0) {
mCircularImageViewAvatar.setBorderWidth(configTheForm.getBorderWidth() * Integer.valueOf(Float.valueOf(getResources().getDisplayMetrics().density).intValue()));
}
// pictures
if (configTheForm.getPictures() != null) {
String baseUrl = configTheForm.getUrlPicto() + configTheForm.getFolder() + File.separator;
String ext = Utils.setExtension(mActivity, Config.PICTURE_EXTENSION);
Pictures pics = configTheForm.getPictures();
if (configTheForm.getPictures().getPictureBack() != null) {
aq.id(mImageButtonClose).image(baseUrl + pics.getPictureBack() + ext, options);
}
if (configTheForm.getPictures().getPictureCamera() != null) {
aq.id(mImageButtonCamera).image(baseUrl + pics.getPictureCamera() + ext, options);
}
if (configTheForm.getPictures().getPictureLibrary() != null) {
aq.id(mImageButtonLibrary).image(baseUrl + pics.getPictureLibrary() + ext, options);
}
if (configTheForm.getPictures().getPicturePublish() != null) {
mImageViewPublish.setVisibility(View.VISIBLE);
aq.id(mImageViewPublish).image(baseUrl + pics.getPicturePublish() + ext, options);
} else {
mImageViewPublish.setVisibility(View.GONE);
}
}
}
mEditTextText.addTextChangedListener(textWatcher);
}
private Range findEditingTag(String text) {
Pattern pattern = Pattern.compile("#[A-z0-9_]+$");
Matcher match = pattern.matcher(text);
if (match.find()) {
String value = text.substring(match.start());
return new Range(match.start(), match.end(), value);
}
return null;
}
private void autocompete(Range range) {
mAutocompleting = range;
mAutocompleteContainer.removeAllViews();
if (range != null && mTags != null) {
String tag;
for (int i = 0; i < mTags.length; i++) {
tag = "#" + mTags[i].getName();
if (tag.startsWith(range.value) && tag.equals(range.value) == false) {
addAutocompleteItem(tag);
}
}
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void addAutocompleteItem(String text) {
Drawable background = mActivity.getResources().getDrawable(R.drawable.autocomplete_item);
int textColor = mActivity.getResources().getColor(R.color.autocomplete_item_text);
TextView view = new TextView(mActivity);
view.setText(text);
view.setTextColor(textColor);
view.setPadding(20, 10, 20, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
view.setLayoutParams(params);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(background);
} else {
view.setBackground(background);
}
view.setClickable(true);
view.setOnClickListener(mAutocompleteItemClickListener);
mAutocompleteContainer.addView(view);
}
private void updateProgress() {
//int progress = 0;
//for (Upload file: mUploading) {
// progress += file.getProgress();
//}
//progress /= mUploading.size();
//mProgressBarFile.setProgress(progress);
//mTextViewFileProgress.setText(String.format(getString(R.string.theform_text_file_progress), Integer.valueOf(progress).toString()));
}
private class S3PutObjectTask extends AsyncTask<Upload, Integer, S3TaskResult> {
//private Dialog progressDialog;
ObjectMetadata mMetadata = new ObjectMetadata();
private String mS3Filename;
private Upload mFile;
#Override
protected void onPreExecute() {
updateProgress();
}
#Override
protected void onProgressUpdate(Integer... values) {
int progress = Integer.valueOf( (int) ((values[0] * 100) / mMetadata.getContentLength()) );
mFile.setProgress(progress);
updateProgress();
super.onProgressUpdate(values);
}
protected S3TaskResult doInBackground(Upload... files) {
if (files == null || files.length != 1 || files[0] == null) {
return null;
} else {
mFile = files[0];
}
ContentResolver resolver = mActivity.getContentResolver();
// The file location of the image selected.
Uri selectedSource = Uri.parse(mFile.path);
if (mFile.type.equals("image")) {
String size = null;
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedSource, fileSizeColumn, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// If the size is unknown, the value stored is null. But since an int can't be
// null in java, the behavior is implementation-specific, which is just a fancy
// term for "unpredictable". So as a rule, check if it's null before assigning
// to an int. This will happen often: The storage API allows for remote
// files, whose size might not be locally known.
if (!cursor.isNull(sizeIndex)) {
// Technically the column stores an int, but cursor.getString will do the
// conversion automatically.
size = cursor.getString(sizeIndex);
}
cursor.close();
}
mMetadata.setContentType(resolver.getType(selectedSource));
if (size != null) {
mMetadata.setContentLength(Long.parseLong(size));
}
}
if (mMetadata.getContentType() == null) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedSource.toString(), opt);
mMetadata.setContentType(opt.outMimeType);
}
if (mMetadata.getContentLength() <= 0) {
mMetadata.setContentLength(new File(selectedSource.toString()).length());
}
selectedSource = Uri.parse("file://" + selectedSource.toString().replace("content://", ""));
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
Calendar cal = Calendar.getInstance();
if (mFile.type.equals("image")) {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".jpg";
} else {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".mp4";
}
PutObjectRequest por = new PutObjectRequest(
Config.getPictureBucket(cal.getTime().getTime()), mS3Filename,
resolver.openInputStream(selectedSource), mMetadata
).withGeneralProgressListener(new ProgressListener() {
int total = 0;
#Override
public void progressChanged(ProgressEvent pv) {
total += (int) pv.getBytesTransferred();
publishProgress(total);
}
});
mS3Client.putObject(por);
result.setName(mS3Filename);
} catch (Exception exception) {
exception.printStackTrace();
result.setName(null);
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
//mProgressBarFile.setProgress(0);
//mTextViewFileProgress.setText("");
// AWS Error
if (result != null && result.getErrorMessage() != null && result.getName() == null) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, result.getErrorMessage());
} else {
// add picture name
mTheFormPictures.add(new Medias(result.getName()));
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/** close activity **/
public void close(View v) {
mActivity.finish();
}
/** select picture **/
public void selectPicture(View v) {
//Intent intent;
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/*if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
if (Build.VERSION.SDK_INT >= 18) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}*/
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/* video/*");
startActivityForResult(intent, RESULT_PHOTO_DISK);
}
/** take picture **/
public void tackePicture(View v) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
}
/** record video **/
public void recordVideo(View v) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
}
/** publish button **/
public void publish(View v) {
// object
WebViewTheFormResult theFormResult = new WebViewTheFormResult(mEditTextText.getText().toString(), mTheFormPictures);
if (theFormResult.isEmpty()) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, getString(R.string.theform_publish_error));
} else {
// intent
Intent dataIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(WebViewActivity.INTENT_OBJECT, (Serializable) theFormResult);
dataIntent.putExtras(bundle);
mActivity.setResult(Activity.RESULT_OK, dataIntent);
mActivity.finish();
}
}
#SuppressLint("NewApi")
public static void actionOnActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
return;
}
if (requestCode != RESULT_PHOTO_APN && requestCode != RESULT_VIDEO_APN) {
requestCode = RESULT_PHOTO_DISK;
}
switch (requestCode) {
case RESULT_PHOTO_DISK:
if (Build.VERSION.SDK_INT >= 18 && data.getData() == null) {
ClipData clipdata = data.getClipData();
for (int i = 0, l = clipdata.getItemCount(); i < l; i++) {
onDiskResult(clipdata.getItemAt(i).getUri());
}
} else {
onDiskResult(data.getData());
}
break;
case RESULT_PHOTO_APN:
onApnPhotoResult(data);
break;
case RESULT_VIDEO_APN:
onApnVideoResult(data);
break;
}
}
private static void onDiskResult(Uri selectedImage) {
InputStream imageStream;
try {
File file = new File(
Environment.getExternalStorageDirectory() + File.separator +
"Android" + File.separator +
"data" + File.separator +
mActivity.getPackageName()
);
if (new File(file.getAbsolutePath()).exists() == false) {
file.mkdirs();
}
imageStream = mActivity.getContentResolver().openInputStream(selectedImage);
Bitmap goodPicture = BitmapFactory.decodeStream(imageStream);
String filePath = file.getAbsoluteFile().toString() + "/" + String.valueOf(Utils.uid()) + Config.PHOTO_TMP_NAME;
try {
//goodPicture = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
FileOutputStream out = new FileOutputStream(filePath);
goodPicture = Bitmap.createScaledBitmap(goodPicture, 800, 600, false);
goodPicture.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
queueFile(filePath, "image");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
}
private static void onApnPhotoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_PHOTO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_VIDEO_APN).toString())) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
} else {
queueFile(filePath, "image");
}
}
private static void onApnVideoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_VIDEO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_PHOTO_APN).toString())) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
} else {
queueFile(filePath, "video");
}
}
private static void queueFile(String filePath, String fileType) {
mQueue.add(new Upload(filePath, fileType));
}
#Override
public void onResume() {
fetchTags();
while (mQueue.size() > 0) {
uploadFile(mQueue.remove(mQueue.size() - 1));
}
super.onResume();
}
private void uploadFile(Upload file) {
new S3PutObjectTask().execute(file);
listFileToUpload.add(file);
mUploading.updateListFileToUpdate(listFileToUpload);
mUploading.notifyDataSetChanged();
}
private void fetchTags() {
Api.getTags(mActivity, new Api.Callback() {
#Override
public void onSuccess(String json) {
Gson gson = new Gson();
mTags = gson.fromJson(json, Tag[].class);
}
});
}
}
How can I resolve the problem?
Something like this should be enough:
...
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
finalHolder.progressUpdate.setProgress(item.getProgress());
}
});
finalHolder.progressUpdate.setProgress(item.getProgress());
Think that you can remove setProgressListener() from Upload class.
Instead add a ProgressBar variable and a method setProgressBar() to Upload.
In getView():
Upload upload = getItem(position )
upload.setProgressBar(holder.progressUpdate);
In Upload: in setProgress() you can now directly address the ProgressBar variable
this is the setProgress() that in your AsyncTask is called with mFile.setProgress(progress);
Instead of removing better out comment the function and the call.
Untested. Please test. This will not be much work.
Don't make holder final. It will not help you. You also made item final in order to use it in onProgress. But that will not do either. You have to determine the right holder with getTag() and if you put position in the holder (as int variable) then you can use holder.position to get the right item again with a getItem(holder.position)
Thanks for your responses all.
I resolved the problem like this:
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
List<Upload> listFileToUpload;
UploadsViewAdapter instanceUploadsViewAdapter;
public UploadsViewAdapter(Context context,
List<Upload> data) {
this.mContext = context;
this.listFileToUpload = data;
this.instanceUploadsViewAdapter = this;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.upload_item, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.play = (ImageView) row.findViewById(R.id.play);
holder.progressUpdate = (ProgressBar) row
.findViewById(R.id.progressUpdate);
holder.deleteFileUploaded = (ImageView) row.findViewById(R.id.delete_file_uploaded);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
//item.setProgress(progress);
finalHolder.progressUpdate.setProgress(progress);
if(progress==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
}
});
if(item.getProgress()==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
holder.deleteFileUploaded.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listFileToUpload.remove(position);
instanceUploadsViewAdapter.notifyDataSetChanged();
}
});
if(item.getType().equals(EnumTypeFile.IMAGE.getTypeFile())){
holder.play.setVisibility(View.GONE);
}
else{
holder.play.setVisibility(View.VISIBLE);
}
finalHolder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
ImageView deleteFileUploaded;
ImageView play;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}

how to convert an class extends activity into independent class

I have a class that is currently extending Activity and I have methods like onCreate(),OnBackPress() etc. I want to turn it into an independent class but all the above methods become undefined. What is the problem? Shouldn't importing the classes be enough? For eg, I import android.view.View for findViewById but it still makes no difference. Please advise.
File_Explore
public class File_Explorer extends Activity {
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
String aDataRow = "";
static StringBuilder aBuffer = new StringBuilder();
String aBuffer1="";
private static final String TAG = "F_PATH";
static long fileSizeInMB;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 0;
static String fileExtension="";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.ic_launcher);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.ic_launcher;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Back", R.drawable.ic_launcher);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablePadding(
fileList[position].icon);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("Back") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
fileExtension
= MimeTypeMap.getFileExtensionFromUrl(sel.toString());
// Toast.makeText(getApplication(), fileExtension, Toast.LENGTH_LONG).show();
long fileSizeInBytes = sel.length();
fileSizeInMB = fileSizeInBytes/(1024*1024);
Toast.makeText(getApplication(), String.valueOf(fileSizeInMB).toString(), Toast.LENGTH_LONG).show();
if(fileSizeInMB >1){
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
}
else{
try{
// ArrayList<String> MyFiles = new ArrayList<String>();
FileInputStream fIn = new FileInputStream(sel);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer.append(aDataRow.toString()).append("\n");
}
// aBuffer1 = aBuffer.toString();
myReader.close();
}catch (FileNotFoundException e)
{e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
finish();
}
}
aBuffer.delete(0, aBuffer.length());
// aBuffer1=null;
}
}
);
break;
}
dialog = builder.show();
return dialog;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i= new Intent(this, File_Selecter.class);
startActivity(i);
}
}

add image to sdcard folder in android

I want to develop an android application that can select multiple images and save them in a folder of sdcard. I could select multiple files but when i want to save them in sdcard folder there is only images name. I have understood it when i tried to show those images using GridView there are no images. Here is my code.....
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.image_selection);
Bundle b=getIntent().getExtras();
directoryName=b.getString("key");
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
// TODO Auto-generated method stub
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
selectImages = selectImages + arrPath[i] + "|";
String sendString=extractString(arrPath[i]);
saveImageToSdCard(sendString,arrPath[i]);
Toast.makeText(getApplicationContext(),
sendString,
Toast.LENGTH_LONG).show();
}
}
}
});
}
public String extractString(String myString)
{
String finalString="";
int index = 0;
int count=0;
char newCharacter[]=new char[50];
char[] charArray = myString.toCharArray();
int length=myString.length();
for (int i = 0; i < length; i++)
{
char charString=charArray[i];
if(charString=='/')
{
index=i;
}
}
for (int i = index+1; i < length; i++)
{
newCharacter[count]=charArray[i];
count++;
}
finalString=String.valueOf(newCharacter);
return finalString;
}
public void saveImageToSdCard(String imageName, String fullPath)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root +"/"+directoryName);
String fname = imageName;
final File file = new File (myDir, fname);
if (file.exists ())file.delete();
try
{
final Bitmap myBitmap=BitmapFactory.decodeFile(fullPath);
new Thread() {
public void run()
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (myBitmap != null)
{
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
}
try {
if (file.createNewFile()) {
//
} else {
//
}
FileOutputStream fo;
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
// result.recycle();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
FileOutputStream stream=new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
stream.flush();
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]){
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.imageview.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder
{
ImageView imageview;
CheckBox checkbox;
int id;
}
how can i solve the problem.Thanks...
It seems there is a similar, already answered question:
How to get path by MediaStore.Images.Media
The solution is in the first comment of the answer.

Categories

Resources