android custom listview with gallery images - android

I'm trying to add all the images contained in a folder in my custom listview, where I show a thumbnail of the photo and a little description.
I've found a lot of examples showing images from URL or drawable folder in Android Studio, but nothing working for me that loads a picture located in /storage/emulated/0/DCIM/Camera/AAAAMMGG_HHMMSS.jpg
Here is my code - MainActivity:
import android.content.ContentValues;
public class MainActivity extends ActionBarActivity implements OnClickListener {
public int PHOTO_REQUEST_CODE = 1;
private Uri fileUri;
private ArrayAdapter<String> adapter;
TextView ceScanResults;
ImageButton btnScan;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View addButton = findViewById(mci);
ArrayList<ListItem> listData = getListData();
final ListView listView = (ListView) findViewById(R.id.custom_list);
listView.setAdapter(new CustomListAdapter(this, listData));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
ListItem newsData = (ListItem) listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
}
});
initViews();
}
private ArrayList<ListItem> getListData() {
ArrayList<ListItem> listMockData = new ArrayList<ListItem>();
String[] images = getResources().getStringArray(R.array.images_array);
String[] headlines = getResources().getStringArray(R.array.headline_array);
for (int i = 0; i < images.length; i++) {
ListItem newsData = new ListItem();
newsData.setUrl(images[i]);
newsData.setHeadline(headlines[i]);
newsData.setReporterName("CE code");
newsData.setDate("28/07/2015 - 10:31");
listMockData.add(newsData);
}
return listMockData;
}
private void initViews() {
//ceScanResults = (TextView) findViewById(R.id.ceResults);
btnScan = (ImageButton) findViewById(R.id.mci);
btnScan.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void initGalleryFetchImage() {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_OK);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Uri selectedImageUri = null;
String filePath = null;
if (requestCode == 1 && resultCode == RESULT_OK ) {
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = fileUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == 2) {
selectedImageUri = intent.getData();
}
if(selectedImageUri != null){
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
// bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.mci) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, PHOTO_REQUEST_CODE);
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
//create new Intent
startActivityForResult(intent, 1);
fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
try ( InputStream is = new URL(filePath).openStream() ) {
Bitmap bitmap = BitmapFactory.decodeStream( is );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
}
}
And the code of my CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListItem newsItem = listData.get(position);
holder.headlineView.setText(newsItem.getHeadline());
holder.reporterNameView.setText("" + newsItem.getReporterName());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reporterNameView;
TextView reportedDateView;
ImageView imageView;
}
}
My class ImageDownloaderTask:
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
My ListItem.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"
>
<ImageView
android:id="#+id/image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:contentDescription="icon"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>
Thanks a lot for your precious support!
Greetings,
Michele.

I'm using this library to load images from an URL
https://github.com/thest1/LazyList

try using code like this in Your adapter:
File img = new File("/sdcard/image.jpg");
if(img.exists()){
Bitmap bitmap = BitmapFactory.decodeFile(img.getAbsolutePath());
holder.imageView.setImageBitmap(bitmap);
}

Related

how can i crop the image and store it in gridview?

i am building a app in which user can capture image from camera and then edit that image and store / display the image in a gridview.the problem i am facing is that when the user capture the image instead of crop the image it directly display it in gridview . i need help in this thanks in advance
this is my code
public class MainActivity extends Activity implements OnClickListener {
Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private List<String> listOfImagesPath;
Intent CropIntent;
public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureBtn = (Button)findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = ( GridView) findViewById(R.id.gridviewimg);
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
public void ImageCropFunction() {
// Image Crop Code
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(picUri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 180);
CropIntent.putExtra("outputY", 180);
CropIntent.putExtra("aspectX", 3);
CropIntent.putExtra("aspectY", 4);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, 1);
} catch (ActivityNotFoundException e) {
}
}
//Image Crop Code End Here
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.capture_btn1) {
try {
//use standard intent to capture an image
Intent captureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support
capturing images!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if(requestCode == CAMERA_CAPTURE){
ImageCropFunction();
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(GridViewDemo_ImagePath);
imageDirectory.mkdirs();
String _path = GridViewDemo_ImagePath + imgcurTime+".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
}
}
private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(GridViewDemo_ImagePath);
if (f.exists()) {
File[] files=f.listFiles();
Arrays.sort(files);
for(int i=0; i<files.length; i++){
File file = files[i];
if(file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}
public class ImageListAdapter extends BaseAdapter
{
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic)
{
context = c;
imgPic = thePic;
}
public int getCount() {
if(imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if(fs!=null) {
bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
}
Let me know if it works
first of all change
startActivityForResult(CropIntent, 1);
to
`startActivityForResult(CropIntent, 2);`
and add to onActivityResult add this:
picUri = Uri.parse(_path);
after that in your onActivityResult remove
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
and add new result like
if(requestCode == CAMERA_CAPTURE){
....
} else if(requestCode == 2){
..
}
and last step in your new statement add this line:
else if(requestCode == 2){
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
https://github.com/ArthurHub/Android-Image-Cropper
Use this library. It's very easy to use

Fragment Upload Image to ImageButton

I have tried many different approaches but none of them seem to help, so the problem is the following:
Image isn't uploading to imageButton. I have the path and I have checked it via debugger, added some Toasts to that the fragment gets to the onActivityResult and it does, but the image isn't uploading. Any ideas?
public class AddProductFragment extends Fragment {
private static final String TAG = "AddProductFragment";
private static final int GALLERY_INTENT = 2;
private Uri imageUri;
private ImageButton imageButton;
private EditText productName,produtPrice,productDescription;
private Button btnCancel,btnAdd;
private FirebaseDatabase mDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDb = FirebaseDatabase.getInstance();
}
private void onClickEvents() {
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i,"Select Picture"),GALLERY_INTENT);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: Edit this;
String name = productName.getText().toString();
String price = produtPrice.getText().toString();
String description = productDescription.getText().toString();
DatabaseOperation dbOps = new DatabaseOperation(mDb,getContext());
dbOps.AddProduct(imageUri,name,price,description);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: exit fragment
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_product, container, false);
imageButton = (ImageButton) v.findViewById(R.id.imageButton2);
productName = (EditText)v.findViewById(R.id.addProduct_productName);
produtPrice = (EditText)v.findViewById(R.id.addProduct_productPrice);
productDescription = (EditText)v.findViewById(R.id.addProduct_productDescription);
btnAdd = (Button) v.findViewById(R.id.addProduct_addBtn);
btnCancel = (Button) v.findViewById(R.id.addProduct_cancelBtn);
onClickEvents();
return v;
}
public Bitmap getBitmap(String path) {
Bitmap bitmap = null;
try {
File f = new File(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
imageButton.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 1", Toast.LENGTH_SHORT).show();
if(requestCode == GALLERY_INTENT){
Toast.makeText(AddProductFragment.this.getActivity(), "Number 2", Toast.LENGTH_SHORT).show();
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 3", Toast.LENGTH_SHORT).show();
String path = getPathFromCameraData(data, this.getActivity());
Toast.makeText(AddProductFragment.this.getActivity(), "Uploading", Toast.LENGTH_SHORT).show();
if (path != null) {
setFullImageFromFilePath( path);
Toast.makeText(AddProductFragment.this.getActivity(), "Uploaded", Toast.LENGTH_SHORT).show();
}
}
}
}
public void setFullImageFromFilePath( String imgPath) {
// btn.setImageBitmap(BitmapFactory.decodeFile(imgPath));
getBitmap(imgPath);
}
public static String getPathFromCameraData(Intent data, Context ctx) {
Uri selectedImage = data.getData();
String[] pathToFile = {MediaStore.Images.Media.DATA};
Cursor cursor = ctx.getContentResolver().query(selectedImage, pathToFile, null,
null, null);
if(cursor == null) return null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(pathToFile[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
}
case GALLERY_INTENT:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageURI(selectedImage);// To display selected image in image view
}

recyclerview footer click to load images

I'm trying to achieve some thing like the image below. Here when recyclerview is empty it will show the camera imageview in footer and when I click on the image, I can select image from camera or gallery (which will be saved in an internal storage folder) and display them in recyclerview. But I'm getting ArrayIndexOutOfBoundsException in onBindViewHolder in case 1. How to display images from internal folder?
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
at java.util.ArrayList.get(ArrayList.java:413)
at com.sam.testapp.ImageAdapter.onBindViewHolder(ImageAdapter.java:85)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6279)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6312)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5258)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5521)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2969)
// Activity
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
RecyclerView recycler;
ImageAdapter adapter;
private ArrayList<Object> itemList;
String[] items = new String [] {"http://i.imgur.com/7P2v384.jpg", "http://i.imgur.com/Fb95GwC.jpg", "http://i.imgur.com/qciJxBg.jpg","http://i.imgur.com/h2jgdAd.jpg"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recycler = (RecyclerView)findViewById(R.id.recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, OrientationHelper.HORIZONTAL, false);
recycler.setLayoutManager(linearLayoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
adapter = new ImageAdapter(MainActivity.this, itemList);
recycler.setAdapter(adapter);
//Collections.addAll(itemList, items);
itemList = new ArrayList<Object>(Arrays.asList(items));
itemList.add(1);
}
}
// Adapter
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_FOOTER = 0;
private static final int TYPE_ITEM = 1;
final CharSequence[] items = {
"Camera", "Gallery", "Cancel"
};
private ArrayList<Object> finalImages = new ArrayList<>();
private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TESTAPP";
public ImageAdapter(Context context, ArrayList<Object> itemList) {
this.finalImages = itemList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v0 = LayoutInflater.from(parent.getContext()).inflate(R.layout.customrowlayout, parent, false);
viewHolder = new VHFooter(v0);
break;
case 1:
View v1 = inflater.inflate(R.layout.imagerowlayout, parent, false);
viewHolder = new VHItem(v1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
VHFooter vh0 = (VHFooter) holder;
vh0.imgv.setImageResource(R.drawable.camera);
vh0.imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
break;
case 1:
VHItem vh1 = (VHItem) holder;
String path = (String) finalImages.get(position);
if (!TextUtils.isEmpty(path)) {
Picasso.with(mContext).load(path).into(vh1.image);
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(intent, 0);
dialog.dismiss();
} else if (item == 1) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, 1);
dialog.dismiss();
} else if (item == 2) {
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
savefile(data, true);
loadfile();
} else if (resultCode == RESULT_OK && requestCode == 1) {
savefile(data, false);
loadfile();
}
}
private void savefile(Intent data, boolean isCamera) {
if (isCamera) {
Bitmap bmap = (Bitmap) data.getExtras().get("data");
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "myimage.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmap = (BitmapFactory.decodeFile(picturePath));
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ENGLISH).format(new Date());
File file = new File(directory, "IMG_" + timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadfile() {
File directory = new File(file_path);
File newfile[] = directory.listFiles();
Log.e("sammy_arrlistsize_befor", " " + finalImages.size());
if (finalImages != null) finalImages.clear();
for (int i = 0; i < newfile.length; i++) {
String path = "file://" + newfile[i].getAbsolutePath();
finalImages.add(path);
Log.e("sammy_imagepath", " " + path);
}
Log.e("sammy_arrlistsize_after", " " + finalImages.size());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return this.finalImages.size();
}
#Override
public int getItemViewType(int position) {
if (finalImages.get(position) instanceof String) {
return TYPE_ITEM;
} else if (finalImages.get(position) instanceof Integer) {
return TYPE_FOOTER;
}
return -1;
}
class VHItem extends RecyclerView.ViewHolder {
ImageView image;
public VHItem(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
class VHFooter extends RecyclerView.ViewHolder {
ImageView imgv;
public VHFooter(View itemView) {
super(itemView);
imgv = (ImageView) itemView.findViewById(R.id.imgv);
}
}
}
First in MainActivity
private ArrayList<Object> itemList = new ArrayList<>();
itemList.addAll(yourStringList);
itemList.add(1);
then use below adapter class
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_FOOTER = 0;
private static final int TYPE_ITEM = 1;
final CharSequence[] items = {
"Camera", "Gallery", "Cancel"
};
private ArrayList<Object> finalImages = new ArrayList<>();
private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TESTAPP";
public ImageAdapter(Context context, ArrayList<Object> itemList) {
this.finalImages = itemList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v0 = LayoutInflater.from(parent.getContext()).inflate(R.layout.customrowlayout, parent, false);
viewHolder = new VHFooter(v0);
break;
case 1:
View v1 = inflater.inflate(R.layout.imagerowlayout, parent, false);
viewHolder = new VHItem(v1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
VHFooter vh0 = (VHFooter) holder;
vh0.imgv.setImageResource(R.drawable.camera);
// Picasso.with(mContext).load(R.drawable.camera).into(vh0.imgv);
//piccaso is commented for now
vh0.imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
break;
case 1:
VHItem vh1 = (VHItem) holder;
String path = (String) finalImages.get(position);
if (!TextUtils.isEmpty(path)) {
Picasso.with(mContext).load(path).into(vh1.image);
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(intent, 0);
dialog.dismiss();
} else if (item == 1) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, 1);
dialog.dismiss();
} else if (item == 2) {
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
savefile(data, true);
loadfile();
} else if (resultCode == RESULT_OK && requestCode == 1) {
savefile(data, false);
loadfile();
}
}
private void savefile(Intent data, boolean isCamera) {
if (isCamera) {
Bitmap bmap = (Bitmap) data.getExtras().get("data");
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "myimage.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmap = (BitmapFactory.decodeFile(picturePath));
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ENGLISH).format(new Date());
File file = new File(directory, "IMG_" + timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadfile() {
File directory = new File(file_path);
File newfile[] = directory.listFiles();
Log.e("sammy_arrlistsize_befor", " " + finalImages.size());
if (finalImages != null) finalImages.clear();
for (int i = 0; i < newfile.length; i++) {
String path = "file://" + newfile[i].getAbsolutePath();
finalImages.add(path);
Log.e("sammy_imagepath", " " + path);
}
Log.e("sammy_arrlistsize_after", " " + finalImages.size());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return this.finalImages.size();
}
#Override
public int getItemViewType(int position) {
if (finalImages.get(position) instanceof String) {
return TYPE_ITEM;
} else if (finalImages.get(position) instanceof Integer) {
return TYPE_FOOTER;
}
return -1;
}
class VHItem extends RecyclerView.ViewHolder {
ImageView image;
public VHItem(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
class VHFooter extends RecyclerView.ViewHolder {
ImageView imgv;
public VHFooter(View itemView) {
super(itemView);
imgv = (ImageView) itemView.findViewById(R.id.imgv);
}
}
}
Your exception is being thrown because
#Override
public int getItemCount() {
return this.finalImages.size()+1;
}
should be
#Override
public int getItemCount() {
return this.finalImages.size();
}

OnClick goto new Activity in GridView Android

I take a photo from the camera and store them in a GridView, now when i view them there is no OnClick function to Enlarge or Goto new Activity to Enlarge the selected image, Here's the code:
Where to implement the OnClick method to take the selected image to a new Activity and enlarge it
package com.example.veeresh.myphotogallery;
public class Photo_1 extends AppCompatActivity implements OnClickListener {
Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private List<String> listOfImagesPath;
private String path;
private String pathMusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
int pos = 0;
path = " ";
pathMusic = getIntent().getStringExtra("Store to Music");
if(pathMusic != null)
{
path = pathMusic;
}
captureBtn = (Button) findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = (GridView) findViewById(R.id.gridviewimg);
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if (listOfImagesPath != null) {
grid.setAdapter(new ImageListAdapter(this, listOfImagesPath));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.capture_btn1) {
try {
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
Toast.makeText(this, "Launching Camera", Toast.LENGTH_SHORT).show();
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if (requestCode == CAMERA_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(path);
imageDirectory.mkdirs();
String _path = path + imgcurTime + ".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if (listOfImagesPath != null) {
grid.setAdapter(new ImageListAdapter(this, listOfImagesPath));
}
}
}
}
private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(path);
if (f.exists()) {
File[] files = f.listFiles();
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}
public class ImageListAdapter extends BaseAdapter {
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic) {
context = c;
imgPic = thePic;
}
public int getCount() {
if (imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; //Disable Dithering mode
bfOptions.inPurgeable = true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if (fs != null) {
bm = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(300, 600));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fs != null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
}
Use setOnItemClickListener of girdview.
grid = (GridView) findViewById(R.id.gridviewimg);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "you clicked at : " + position, Toast.LENGTH_LONG).show();
// put your intent here to open activity
}
});
put this code inside your onCreate(...) method.
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// do your stuff.
}
});

How to send image to FTP Client in android?

I am developing an android application in that i need to send my image to the Specific FTP URL address can any one help me how can I do that please.
URL is:
http://demo1.idevtechnolabs.com/RChatAPI/usrPhotos/
And My Code is:
public class ImageGallery extends Activity
{
private static final int PICK_IMAGE = 1;
private static final int PICK_Camera_IMAGE = 2;
private ImageView imgView;
private Button upload,cancel;
private Bitmap bitmap;
private ProgressDialog dialog;
Uri imageUri;
Uri selectedImageUri = null;
String filePath = null;
MediaPlayer mp=new MediaPlayer();
Handler progressHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.imguploadbtn);
cancel = (Button) findViewById(R.id.imgcancelbtn);
upload.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (bitmap == null)
{
Toast.makeText(getApplicationContext(),"Please select image", Toast.LENGTH_SHORT).show();
}
else
{
dialog = ProgressDialog.show(ImageGallery.this, "Uploading","Please wait...", true);
new ImageGalleryTask().execute();
}
}
});
cancel.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
ImageGallery.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_image_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.camera:
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
return true;
case R.id.gallery:
try
{
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gintent, "Select Picture"),PICK_IMAGE);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK)
{
selectedImageUri = data.getData();
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK)
{
//use imageUri here to access the image
selectedImageUri = imageUri;
/*Bitmap mPic = (Bitmap) data.getExtras().get("data");
selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));*/
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null)
{
try
{
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
{
filePath = selectedImagePath;
}
else if (filemanagerstring != null)
{
filePath = filemanagerstring;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null)
{
decodeFile(filePath);
}
else
{
bitmap = null;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
class ImageGalleryTask extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... unsued)
{
FTPClient ftpClient = new FTPClient();
try
{
ftpClient.connect(InetAddress.getByName("My URL Address"));
ftpClient.login("My Username", "My Password");
ftpClient.changeWorkingDirectory("My Path of URL");
if (ftpClient.getReplyString().contains("250"))
{
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn = null;
String path=selectedImageUri.toString();
Log.v("Image Path:",filePath);
buffIn = new BufferedInputStream(new FileInputStream(filePath));
ftpClient.enterLocalPassiveMode();
ProgressInputStream progressInput = new ProgressInputStream(buffIn, progressHandler);
boolean result=ftpClient.storeUniqueFile(progressInput);
boolean result = ftpClient.storeFile(localAsset.getFileName(), progressInput);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
}
catch (Exception e)
{
Log.d("Error in ftp:",e.toString());
}
return "Success";
}
#Override
protected void onProgressUpdate(Void... unsued)
{
}
#Override
protected void onPostExecute(String sResponse)
{
try
{
if (dialog.isShowing())
dialog.dismiss();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null)
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else
return null;
}
public void decodeFile(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
imgView.setImageBitmap(bitmap);
}
}
When I use this code and click on upload button
I got the following error:
Could not find class 'org.apache.commons.net.ftp.FTPClient', referenced from method com.androidmyway.demo.imagedemo.ImageGallery$ImageGalleryTask.doInBackground
Try using this simple example to upload any file over webserver from here.
You have to add a dependency for using FTPClient class. You can find it easily on anywhere. it is "commons apache" named dependency.

Categories

Resources