I want to set images into into gridview from SD card? - android

Below is my AppConstant.java
package com.domore.gridviewtutorial.helper;
import java.util.Arrays;
import java.util.List;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class AppContant {
// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;
// Gridview image padding
public static final int GRID_PADDING = 8; // in dp
// SD card image directory
public static final String PHOTO_ALBUM = "MyPhotos";
// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
"png");
}
in this class i set the file extension which i load in my app
Here, is my utils class
package com.domore.gridviewtutorial.helper;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class Utils {
private Context context;
public Utils(Context context){
this.context=context;
}
public ArrayList<String> getFilePaths(){
ArrayList<String> filePaths=new ArrayList<String>();
File directory=new File(android.os.Environment.getExternalStorageDirectory()+File.separator+AppContant.PHOTO_ALBUM);
if(directory.isDirectory()){
File[] listFiles=directory.listFiles();
if(listFiles.length > 0 ){
for(int i=0;i<listFiles.length;i++){
String filePath=listFiles[i].getAbsolutePath();
if(IsSupportedFile(filePath)){
filePaths.add(filePath);
}
}
}
else{
Toast.makeText(
context,
AppContant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
}
else{
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Error!");
alert.setMessage(AppContant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppContant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
Here is my grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000">
</GridView>
i have Adapter class to load images
package com.domore.gridviewtutorial.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.GridView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.view.View.OnClickListener;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> _filePaths=new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity,ArrayList<String> _filePaths,int imageWidth){
this.activity=activity;
this._filePaths=_filePaths;
this.imageWidth=imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView==null){
imageView=new ImageView(this.activity);
}
else{
imageView=(ImageView)convertView;
}
Bitmap image=decodeFile(this._filePaths.get(position),imageWidth,imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Intent i = new Intent(activity, FullScreenViewActivity.class);
// i.putExtra("position", _postion);
// activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Here is my MainActivity.java
package com.domore.gridviewtutorial;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.GridLayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.domore.gridviewtutorial.adapter.GridViewImageAdapter;
import com.domore.gridviewtutorial.helper.AppContant;
import com.domore.gridviewtutorial.helper.Utils;
import java.util.ArrayList;
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
I got error in mainActivity.java
here is my error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setNumColumns(int)' on a null object reference
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.InitilizeGridLayout(AndroidGridLayoutActivity.java:46)
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:34)
can anyone who help me to solve out this error i cannot able to understand.

Your gridView variable is null because you are recreating the a new variable gridView in your onCreate() method and your's activity's instance gridView variable is never get Initialized.
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// initiated the gridView variable
gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}

Related

Is there any control over Carousel viewpager item position?

I have already implemented Carousel Viewpager ...but I m stuck at one point.
There is 10 image item in ArrayList ...First 3 item (0,1,2 position) are showing and we can scroll horizontally one by one
What I want, When I click on first position i.e, 0 it should go position 1 and when I click on position 2, it should come position 1.
How can I achieve this?enter image description here
Method in mainActivity
private void showDrinkList() {
try {
DisplayMetrics metrics = new DisplayMetrics();
Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
int pageMargin = ((metrics.widthPixels / 3) * 2);
pager.setPageMargin(-pageMargin);
CarouselPagerAdapter adapter = new CarouselPagerAdapter(context,this.getChildFragmentManager(), this.getChildFragmentManager(), pager, drinkLists);
pager.setAdapter(adapter);
pager.addOnPageChangeListener(adapter);
if (drinkLists.size() > 1)
pager.setCurrentItem(1);
pager.setOffscreenPageLimit(3);
pager.setHorizontalScrollBarEnabled(true);
} catch (Exception e) {
e.printStackTrace();
} }
Carousel Adapter -
import android.content.Context;
import android.graphics.Interpolator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.List;
import ae.frink.android.R;
import ae.frink.android.app.customDialog.RedeemDialog;
import ae.frink.android.model.BeanDrinkImage;
import ae.frink.android.utils.FixedSpeedScroller;
import ae.frink.android.utils.ViewPagerCustomDuration;
public class CarouselPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
public final static float BIG_SCALE = 0.8f;
private final static float SMALL_SCALE = 0.4f;
private final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;
private FragmentManager context;
private Context c;
private FragmentManager fragmentManager;
private float scale;
public static ViewPager viewPager;
private List<BeanDrinkImage.DrinkList> drinkLists;
private CarouselPagerAdapter adapter;
//private ItemFragment itemFragment;
public CarouselPagerAdapter(Context c, FragmentManager context, FragmentManager fm, ViewPager viewPager,
List<BeanDrinkImage.DrinkList> drinkLists) {
super(fm);
this.fragmentManager = fm;
this.context = context;
this.c = c;
// this.itemFragment = new ItemFragment(drinkLists);
this.viewPager = viewPager;
this.drinkLists = drinkLists;}
#Override
public Fragment getItem(int position) {
// make the first pager bigger than others
try {
if (position == 0) //BarInformationFrag.FIRST_PAGE)
scale = SMALL_SCALE;
else if(position == 1)
scale = BIG_SCALE;
else if(position == 2)
scale = SMALL_SCALE;
else
scale = SMALL_SCALE;
position = position % drinkLists.size();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("drinkSize", "....----" + drinkLists.size());
// ItemFragment itemFragment = new ItemFragment();
return ItemFragment.newInstance(context, position, scale, drinkLists);
}
#Override
public int getCount() {
// int count = 0;
// try {
// count = BarInformationFrag.count * BarInformationFrag.LOOPS;
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// }
// return count;
return drinkLists.size();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
try {
if (positionOffset >= 0f && positionOffset <= 1f) {
CarouselLinearLayout cur = getRootView(position);
CarouselLinearLayout next = getRootView(position + 1);
cur.setScaleBoth(BIG_SCALE - DIFF_SCALE * positionOffset);
next.setScaleBoth(SMALL_SCALE + DIFF_SCALE * positionOffset);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#SuppressWarnings("ConstantConditions")
private CarouselLinearLayout getRootView(int position) {
return (CarouselLinearLayout) fragmentManager.findFragmentByTag(this.getFragmentTag(position))
.getView().findViewById(R.id.root_container);
}
private String getFragmentTag(int position) {
return "android:switcher:" + viewPager.getId() + ":" + position;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Carousel Linear Layout -
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class CarouselLinearLayout extends LinearLayout {
private float scale = CarouselPagerAdapter.BIG_SCALE;
// private float scale = .5f;
public CarouselLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CarouselLinearLayout(Context context) {
super(context);
}
public void setScaleBoth(float scale) {
this.scale = scale;
this.invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// The main mechanism to display scale animation, you can customize it as your needs
int w = this.getWidth();
int h = this.getHeight();
canvas.scale(scale, scale, w / 2, h / 2);
}
}
item Fragment -
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import ae.frink.android.R;
import ae.frink.android.app.customDialog.RedeemDialog;
import ae.frink.android.connection.ApiClient;
import ae.frink.android.model.BeanDrinkImage;
import static ae.frink.android.Carousel.CarouselPagerAdapter.viewPager;
public class ItemFragment extends Fragment {
private static final String POSITON = "position";
private static final String SCALE = "scale";
private static final String DRAWABLE_RESOURE = "resource";
private static final String DRINK_LIST = "drinkList";
private List<BeanDrinkImage.DrinkList> dL;
private static final String IMAGE = "image";
public ArrayList<Integer> imageArray;
private Context context;
private List<BeanDrinkImage.DrinkList> drinkLists;
private SharedPreferences sharedPreferences;
private int screenWidth;
private int screenHeight;
/* private int[] imageArray = new int[]{R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1,
R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1,
R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1,
R.drawable.cocktail_lime_gin_fizz_1, R.drawable.cocktail_lime_gin_fizz_1};
*/
public ItemFragment() {
}
/*
#SuppressLint("ValidFragment")
public ItemFragment(List<BeanDrinkImage.DrinkList> drinkLists) {
this.drinkLists = drinkLists;
}
*/
public static Fragment newInstance(FragmentManager context, int pos, float scale, List<BeanDrinkImage.DrinkList> dL) {
ItemFragment fr = new ItemFragment();
Bundle b = new Bundle();
b.putInt(POSITON, pos);
b.putFloat(SCALE, scale);
b.putParcelableArrayList(DRINK_LIST, (ArrayList) dL);
//drinkLists=dL;
// this.context = context;
// this.dL = dL;
// b.putIntegerArrayList(IMAGE, imageArray);
Log.e("drinkSize", "....+++"+dL.size());
fr.setArguments(b);
return fr;//frFragment.instantiate(context, ItemFragment.class.getName(), b);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWidthAndHeight();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
context = getActivity();
final int postion = this.getArguments().getInt(POSITON);
float scale = this.getArguments().getFloat(SCALE);
this.imageArray = this.getArguments().getIntegerArrayList(IMAGE);
drinkLists = (ArrayList) this.getArguments().getParcelableArrayList(DRINK_LIST);
// TODO 21 sep changes
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(screenWidth / 3,
// h/4);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(screenWidth / 2,
screenWidth/2);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.fragment_image, container, false);
TextView textView = (TextView) linearLayout.findViewById(R.id.text);
CarouselLinearLayout root = (CarouselLinearLayout) linearLayout.findViewById(R.id.root_container);
ImageView imageView = (ImageView) linearLayout.findViewById(R.id.pagerImg);
ImageView starImage = (ImageView) linearLayout.findViewById(R.id.imgStar);
imageView.setLayoutParams(layoutParams);
String imageUrl = "";
try {
Log.e("drinkSize", "...."+drinkLists.size());
if (drinkLists.size() > 0) {
imageUrl = ApiClient.IMAGE_URL + drinkLists.get(postion).getImage();
Picasso.get().load(imageUrl).into(imageView);
Log.e("drinkName", drinkLists.get(postion).getDrinkName());
textView.setText(drinkLists.get(postion).getDrinkName());
if (drinkLists.get(postion).getIs_recomended() == 1) {
starImage.setVisibility(View.VISIBLE);
} else {
starImage.setVisibility(View.INVISIBLE);
}
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity() != null) {
RedeemDialog redeemDialog = new RedeemDialog(getActivity(), drinkLists, postion);
redeemDialog.setCanceledOnTouchOutside(true);
redeemDialog.show();
// 12-march
/* if (sharedPreferences.getString(CommonVar.IS_SUBSCRIBED, "0").equals("0")) {
Toast.makeText(getContext(), "Please subscribe first", Toast.LENGTH_SHORT).show();
} else {
RedeemDialog redeemDialog = new RedeemDialog(getActivity(), list, postion);
redeemDialog.setCanceledOnTouchOutside(true);
redeemDialog.show();
}*/
}
}
});
root.setScaleBoth(scale);
} catch (Exception e) {
e.printStackTrace();
}
return linearLayout;
}
/**
* Get device screen width and height
*/
private void getWidthAndHeight() {
DisplayMetrics displaymetrics = new DisplayMetrics();
try {
Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (position == 0) {
scale = SMALL_SCALE;}
else if(position == 1){
scale = BIG_SCALE;
}
else if(position == 2)
{
scale = SMALL_SCALE;
}
else{
scale = SMALL_SCALE;
}
holder.setIsRecyclable(false);

Why am I getting "cannot resolve symbol urlDrawable" in this class

I'm trying to display <img> tags in json string and I using the accepted answer in this question but Android Studio is complaining "cannot resolve symbol urlDrawable
Please can anybody tell me why this is happening and how to fix it?
UILImageGetter
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.View;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
urlDrawable;
public UILImageGetter(View textView, Context context) {
this.c = context;
this.conatiner = (TextView) textView;
}
#Override
public Drawable getDrawable(String source) {
urlDrawable = new UrlImageDownloader(c.getResources(), source);
urlDrawable.drawable = c.getResources().getDrawable(R.drawable.default_thumb);
ImageLoader.getInstance().loadImage(source, new SimpleListener(urlDrawable));
return urlDrawable;
}
private class SimpleListener extends SimpleImageLoadingListener {
UrlImageDownloader mUrlImageDownloader;
public SimpleListener(UrlImageDownloader downloader) {
super();
mUrlImageDownloader= downloader;
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
int width = loadedImage.getWidth();
int height = loadedImage.getHeight();
int newWidth = width;
int newHeight = height;
if (width > conatiner.getWidth()) {
newWidth = conatiner.getWidth();
newHeight = (newWidth * height) / width;
}
if (view != null) {
view.getLayoutParams().width = newWidth;
view.getLayoutParams().height = newHeight;
}
Drawable result = new BitmapDrawable(c.getResources(), loadedImage);
result.setBounds(0, 0, newWidth, newHeight);
mUrlImageDownloader.setBounds(0, 0, newWidth, newHeight);
mUrlImageDownloader.mDrawable = result;
conatiner.setHeight((conatiner.getHeight() + result.getIntrinsicHeight()));
conatiner.invalidate();
}
}
private class UrlImageDownloader extends BitmapDrawable {
public Drawable mDrawable;
public UrlImageDownloader(Resources resources, String filepath) {
super(resources, filepath);
mDrawable = new BitmapDrawable(resources, filepath);
}
#Override
public void draw(Canvas canvas) {
if (mDrawable != null) {
mDrawable.draw(canvas);
}
}
}
}
You haven't assigned a type to urlDrawable;
This portion of code contains the error:
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
urlDrawable;
Try this:
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
UrlImageDownloader urlDrawable;
Java is a strongly typed language, which means that all variables must be declared as being of some type.
Since you don't specify a type for urlDrawable, the compiler doesn't understand that you're declaring a variable.
Simply replace
urlDrawable;
with
UrlImageDownloader urlDrawable;

Android images gridview

The code to display the images from sd card and whatsapp in the app but when I run the code the pictures are displayed but there are random whitespaces between photos and the photos are not of the same size. How do I resize the image ? Heres the code for the main activity:
import java.io.File;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ImageAdapter imageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
imageAdapter = new ImageAdapter(this);
gridview.setAdapter(imageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";
File f=new File(Environment.getExternalStorageDirectory()+"/WhatsApp");
if(f.exists()){
String path=Environment.getExternalStorageDirectory()+"/WhatsApp/Media/WhatsApp Images";
File t=new File(path);
File[] fo=t.listFiles();
for(File fil : fo){
imageAdapter.add(fil.getAbsolutePath());
}
}
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
imageAdapter.add(file.getAbsolutePath());
}
}
Heres the code for image adapter:
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context context;
ArrayList<String> imageList = new ArrayList<String>();
public ImageAdapter(Context c) {
context = c;
}
void add(String path){
imageList.add(path);
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(100,100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 100,100);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
As I said before, the code runs but the sizee of the image is not uniform and there are whitespaces. Please help me solve it.
try to set the scale type fit_xy
imageView.setScaleType(ImageView.ScaleType.FIT_XY);

One class cannot extend two classes

Hey :) I have a code of a ball that using the motion sensor and I want to make my app count time and when you lose, save this time for a record, so I did it, but my problem is, I can't extend my fragment layout, here is my full code:
package com.example.theball;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
#SuppressLint("NewApi") public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
#SuppressWarnings("unused")
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
public static final int width = 50;
public static final int height = 50;
public boolean firstDraw = true;
private int screen_width;
private int screen_height;
private int sensorX;
private Timer t;
private int TimeCounter = 0;
private int sensorY;
private static int score = 0;
private static SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
t=new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TimeCounter++;
}
});
}
}, 0, 1000);
}
public static class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
TextView highscore_int = (TextView)v.findViewById(R.id.highscore_int );
score = prefs.getInt("key", 0);
highscore_int.setText("Highscore:" + score +" seconds.");
return v;
}
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
sensorY = (int) event.values[1];
sensorX = (int) event.values[0];
x -= sensorX*3;
y += sensorY*3;
if(x <= 0 || x >= screen_width || y <= 0 || y >= screen_height) {
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int oldScore = prefs.getInt("key", 0);
if( TimeCounter > oldScore ){
Editor edit = prefs.edit();
edit.putInt("key", TimeCounter);
edit.commit(); }
Intent myIntent = new Intent(this, YouLost.class);
startActivity(myIntent);
}
}
}
public class AnimatedView extends ImageView {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
static final int width = 50;
static final int height = 50;
#SuppressLint("NewApi")
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
display.getSize(size);
screen_width = size.x;
screen_height = size.y;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(0, 0, screen_width, screen_height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
if(firstDraw) {
x = screen_width / 2;
y = screen_height / 2;
firstDraw = false;
}
mDrawable.draw(canvas);
invalidate();
}
}
}
XML FILE:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/highscore_int"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:layout_weight="0.14"
android:text="12312312"
android:textColor="#android:color/black"
android:textSize="40sp" />
</LinearLayout>
I can't see the highscore_int on my device, only at the eclipse xml file grahpic layout.
You have defined MainActivity twice. Rename the second one to e.g. MainFragment (or something else) and you should be fine.
But I would also recommend to move the Fragment to a different file as well.

ParallaxViewPager Right to Left

I am working a project on ParallaxViewPager. I have 3 pages. Everything working normal and the background is parallax as supposed to. But when I add parallaxViewPager.setCurrentItem(2); the background does not appear and it gets default android background. Here is the full code:
MainActivity:
package com.example.myapplication3.app;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.RelativeLayout;
import com.andraskindler.parallaxviewpager.ParallaxViewPager;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ParallaxViewPager parallaxViewPager = ((ParallaxViewPager) findViewById(R.id.parallaxviewpager));
parallaxViewPager.setOverlapPercentage(0.25f);
parallaxViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
parallaxViewPager.setCurrentItem(2);
}
}
PagerAdapter:
package com.example.myapplication3.app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new view1());
fragments.add(new view2());
fragments.add(new view3());
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
View 1,2,3:
package com.example.myapplication3.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class view1 extends Fragment { //view2, view3 on the others
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view1, container, false); //same here view 2,3
return rootView;
}
}
and the layouts are:
MainActivitys' layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
<com.andraskindler.parallaxviewpager.ParallaxViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parallaxviewpager"
android:layout_width="match_parent"
android:background="#drawable/sanfran"
android:layout_height="match_parent"/>
</RelativeLayout>
View 1,2,3' layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Thanks in advance for your time and help.
I had the same problem with this component. It something like a conflict between the canvas and the destination rect so anything is drawn where it should be done.
I made a fork of the original source repository to update it. When setCurrentItem is invoked I check the position and store an adjust value that I use later in the onDraw method.
You can check it at https://github.com/yuraksisa/parallaxviewpager
Here is a modification of the ParallaxViewPager:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
#SuppressLint("NewApi")
public class ParallaxViewPager extends ViewPager {
public static final int FIT_WIDTH = 0;
public static final int FIT_HEIGHT = 1;
public static final float OVERLAP_FULL = 1f;
public static final float OVERLAP_HALF = 0.5f;
public static final float OVERLAP_QUARTER = 0.25f;
public Bitmap bitmap;
private Rect source, destination;
private int scaleType;
private Paint paint;
private OnPageChangeListener secondOnPageChangeListener;
public ParallaxViewPager(Context context) {
super(context);
init();
}
public ParallaxViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
source = new Rect();
destination = new Rect();
scaleType = FIT_HEIGHT;
setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (bitmap != null) {
if (position == 0) {
source.left = (int) ((getWidth() / 8) * positionOffset);
source.right = getWidth() + source.left;
destination.left = (int) ((getWidth() * positionOffset) - getWidth());
destination.right = (int) (0 + (getWidth() * positionOffset));
} else {
source.left = (int) ((getWidth() / 8) - (getWidth() / 8)
* positionOffset);
source.right = getWidth() + source.left;
destination.left = (int) ((0 - getWidth()
* positionOffset));
destination.right = (int) (getWidth() - (getWidth() * positionOffset));
}
postInvalidate();
}
if (secondOnPageChangeListener != null) {
secondOnPageChangeListener.onPageScrolled(position,
positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageSelected(int position) {
if (secondOnPageChangeListener != null) {
secondOnPageChangeListener.onPageSelected(position);
}
}
#Override
public void onPageScrollStateChanged(int state) {
if (secondOnPageChangeListener != null) {
secondOnPageChangeListener.onPageScrollStateChanged(state);
}
}
});
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
destination.top = 0;
destination.bottom = h;
if (getAdapter() != null && bitmap != null)
calculateParallaxParameters();
}
private void calculateParallaxParameters() {
if (bitmap.getWidth() < getWidth()
&& bitmap.getWidth() < bitmap.getHeight()
&& scaleType == FIT_HEIGHT) {
Log.w(ParallaxViewPager.class.getName(),
"Invalid bitmap bounds for the current device, parallax effect will not work.");
}
source.top = 0;
source.bottom = bitmap.getHeight();
}
/**
* Sets the background from a resource file.
*
* #param resid
*/
#Override
public void setBackgroundResource(int resid) {
bitmap = BitmapFactory.decodeResource(getResources(), resid);
}
/**
* Sets the background from a Drawable.
*
* #param background
*/
#Override
public void setBackground(Drawable background) {
bitmap = ((BitmapDrawable) background).getBitmap();
}
/**
* Deprecated. Sets the background from a Drawable.
*
* #param background
*/
#Override
public void setBackgroundDrawable(Drawable background) {
bitmap = ((BitmapDrawable) background).getBitmap();
}
/**
* Sets the background from a bitmap.
*
* #param bitmap
* #return The ParallaxViewPager object itself.
*/
public ParallaxViewPager setBackground(Bitmap bitmap) {
this.bitmap = bitmap;
return this;
}
public ParallaxViewPager setScaleType(final int scaleType) {
if (scaleType != FIT_WIDTH && scaleType != FIT_HEIGHT)
throw new IllegalArgumentException(
"Illegal argument: scaleType must be FIT_WIDTH or FIT_HEIGHT");
this.scaleType = scaleType;
return this;
}
/**
* Sets the amount of overlapping with the setOverlapPercentage(final float
* percentage) method. This is a number between 0 and 1, the smaller it is,
* the slower is the background scrolling.
*
* #param percentage
* #return The ParallaxViewPager object itself.
*/
public ParallaxViewPager setOverlapPercentage(final float percentage) {
if (percentage <= 0 || percentage >= 1)
throw new IllegalArgumentException(
"Illegal argument: percentage must be between 0 and 1");
return this;
}
/**
* Recalculates the parameters of the parallax effect, useful after changes
* in runtime.
*
* #return The ParallaxViewPager object itself.
*/
public ParallaxViewPager invalidateParallaxParameters() {
calculateParallaxParameters();
return this;
}
#Override
protected void onDraw(Canvas canvas) {
if (bitmap != null) {
canvas.drawBitmap(bitmap, source, destination, paint);
}
}
public void addOnPageChangeListener(OnPageChangeListener listener) {
secondOnPageChangeListener = listener;
}
}
And here is how to use:
viewPager = (ParallaxViewPager)findViewById(R.id.lock_viewpager);
viewPager.setBackgroundDrawable(new BitmapDrawable());
viewPager.setAdapter(new MyViewPagerAdapter());
viewPager.addOnPageChangeListener(this);
viewPager.setCurrentItem(mList.size());

Categories

Resources