Cannot cast EditText into TextView in a custom adapter - java

we're currently working on a project and can't get through this weird NullPointerException. We have to cast a specific EditText into a TextView to get our GridView to work. Problem right now is that all tutorials seem to use an Activity, while we're using a Fragment. Our "MainActivity" is just here to initilize some starter things (Splash Screen, Intro Slider etc.). All the other stuff happens in our "HomeFragment". The goal is to capture a picture, write a title and some content, and then save it into a SQLite Database, which can be used to show it in a GridView later on.
We used this guys(github) template to create our own db (and rewrote some stuff because we're using Fragments, of course).
Bear with us while reading the code, it is not finalized yet. Tons of junk code still inside.
FragmentHome.class
public class FragmentHome extends Fragment {
private ImageButton mUnicornButton;
private ImageButton mBaseballbatButton;
private ImageButton mExplosionButton;
private ImageButton mCowButton;
private ImageButton mShitButton;
private ImageButton mPenguinButton;
private final int REQUEST_GALLERY_CODE = 999;
EditText edtTitle, edtContent;
Button btnAdd, btnChoose;
private ImageView mImageView;
protected View mView;
private static final int CAMERA_REQUEST = 1888;
public FragmentHome() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public static SQLiteHelper sqLiteHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
this.mView = v;
initUI(v);
sqLiteHelper = new SQLiteHelper(getActivity().getApplicationContext(), "ListDB.sqlite",null,1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS DBLIST(Id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, content VARCHAR, image BLOB)");
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_GALLERY_CODE);
}
});
Button photoButton = v.findViewById(R.id.add_foto);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
sqLiteHelper.insertData(
edtTitle.getText().toString().trim(),
edtContent.getText().toString().trim(),
imageViewToByte(mImageView)
);
Toast.makeText(getActivity().getApplicationContext(),"Added",Toast.LENGTH_SHORT).show();
edtTitle.setText("");
edtContent.setText("");
mImageView.setImageResource(R.mipmap.ic_launcher_round);
} catch(Exception e){
e.printStackTrace();
}
}
});
return v;
}
private byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,0,stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
if(requestCode == REQUEST_GALLERY_CODE){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_GALLERY_CODE);
}
else {
Toast.makeText(getActivity().getApplicationContext(),"No Permissions",Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST){
if(resultCode == Activity.RESULT_OK){
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
mImageView.setImageBitmap(bitmap);
}
}
}
private void initUI(View v) {
[...] //initializes everything using findViewById()
}
}
DBListAdapter.class (our custom adapter)
public class DBListAdapter extends BaseAdapter{
private Context context;
private int layout;
private ArrayList<DBList> dblistsList;
public DBListAdapter(Context context, int layout, ArrayList<DBList> dblistsList) {
this.context = context;
this.layout = layout;
this.dblistsList = dblistsList;
}
#Override
public int getCount() {
return dblistsList.size();
}
#Override
public Object getItem(int position) {
return dblistsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
ImageView imageView;
TextView txtTitle, txtContent;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtTitle = row.findViewById(R.id.input_title);
holder.txtContent = row.findViewById(R.id.input_content);
holder.imageView = row.findViewById(R.id.fotoView);
row.setTag(holder);
}
else{
holder = (ViewHolder) row.getTag();
}
DBList dbList = dblistsList.get(position);
holder.txtTitle.setText(dbList.getTitle());
holder.txtContent.setText(dbList.getContent());
byte[] dblistImage = dbList.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(dblistImage, 0, dblistImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
The problem is in this Adapter.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at s***.d***.u***.th***ive.DBListAdapter.getView(DBListAdapter.java:78)
We can't figure out how to cast the EditText from the fragment_home.xml into a TextView, which is needed for the ViewHolder.
fragment_home.xml
[...]
<ImageView
android:id="#+id/fotoView"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/Gainsboro"
app:srcCompat="#android:drawable/ic_menu_camera" />
<EditText
android:id="#+id/input_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:inputType="text"
android:maxLines="1"
android:textAlignment="center"
android:layout_above="#+id/input_content"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/input_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_what"
android:inputType="textMultiLine"
android:textAlignment="center"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true"
android:layout_marginBottom="33dp" /> [...]
Any help would be appreciated, my mind is burning right now, I certaintly have no clue how to solve this. If you need more, just ask me. Kinda tired right now, so probably gonna replay late.

okey .. Firstly you need to create new xml file and name it as you want ... let assume that it's name is list_reycle_view then transfer those views to it
<ImageView
android:id="#+id/fotoView"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/Gainsboro"
app:srcCompat="#android:drawable/ic_menu_camera" />
<EditText
android:id="#+id/input_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:inputType="text"
android:maxLines="1"
android:textAlignment="center"
android:layout_above="#+id/input_content"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/input_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_what"
android:inputType="textMultiLine"
android:textAlignment="center"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true"
android:layout_marginBottom="33dp" />
then .. replace these lines
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
with this line
row= LayoutInflater.from(context).inflate(R.layout.list_recycle_view,viewGroup,false);
and run your program

ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder = new ViewHolder();
holder.txtTitle = row.findViewById(R.id.input_title);
holder.txtContent = row.findViewById(R.id.input_content);
holder.imageView = row.findViewById(R.id.fotoView);
row.setTag(holder);
}

Related

How can I transfer image new intent

This is my adapter and I save my image string type in Responsemodel class.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myviewholder>
{
List<ResponseModel> data;
private final IOtobusSaatleriInterface iOtobusSaatleriInterface;
Context context;
public MyAdapter(List<ResponseModel> data, IOtobusSaatleriInterface iOtobusSaatleriInterface, Context context) {
this.data = data;
this.iOtobusSaatleriInterface = iOtobusSaatleriInterface;
this.context = context;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerowdesign,parent,false);
return new myviewholder(view,iOtobusSaatleriInterface);
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.t1.setText(data.get(position).getName());
holder.t2.setText(data.get(position).getDesig());
Glide.with(holder.t1.getContext())
.load("http://example.site/Gurpinar/images/" +data.get(position).getImage()).into(holder.img);
}
#Override
public int getItemCount() {
return null!=data?data.size():0;
}
class myviewholder extends RecyclerView.ViewHolder{
ImageView img;
TextView t1,t2;
public myviewholder(#NonNull View itemView, IOtobusSaatleriInterface iOtobusSaatleriInterface) {
super(itemView);
img = itemView.findViewById(R.id.img);
t1 = itemView.findViewById(R.id.t1);
t2 = itemView.findViewById(R.id.t2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (iOtobusSaatleriInterface != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION);
iOtobusSaatleriInterface.onItemClick(position);
Intent intent = new Intent(context,deneme.class);
intent.putExtra("name",data.get(position).getName());
intent.putExtra("resim","http://example.site/Gurpinar/images/");
context.startActivity(intent);
}
}
});
}
}
}
and my new empty activity
public class deneme extends AppCompatActivity {
TextView textView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deneme);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String goruntu = intent.getStringExtra("resim");
String.valueOf(Glide.with(imageView).load(goruntu));
textView.setText(name);
}
}
And my new empty activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".deneme">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:gravity="left"
android:text="TextView"
android:textColor="#494545"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/imageView" />
</LinearLayout>
My problem is I can access name data but image cannot be displayed.
How can I access the selected photo? I take the photos in mysql database and with the url recyclerview.
Perhaps you can pass the image as a Base64 in the Intent and create in the new Activity a Imagefile from this String.
Create as Base64 String:
How to get raw string of an image from Bitmap in android?
Create the Imagefile again from the String:
Create image file from raw string data

Android: GridView shows all but a few images

I have 6 images downloaded as shown here, but the GridView in my gallery only displays 5 of those images.
I'm trying to copy how Instagram displays its gallery, with a selected image taking up 60% of the screen and the gallery images taking up the rest.
fragment_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relLayoutl">
<!--toolbar-->
<include layout="#layout/snippet_top_gallerybar"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:layout_below="#+id/relLayoutl">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/galleryImageView"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/progressBar"
android:layout_centerInParent="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40">
<GridView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="5"
android:verticalSpacing="1.5dp"
android:horizontalSpacing="1.5dp"
android:gravity="center"
android:layout_marginTop="1dp"
android:stretchMode="none"
android:id="#+id/gridView">
</GridView>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
I created a square view to generate square cells
layout_grid_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.example.sheldon.instagramclone.Util.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridViewImage"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:id="#+id/gridProgressBar"/>
</RelativeLayout>
GalleryFragment.java
public class GalleryFragment extends Fragment {
private static final int NUM_COLUMNS = 4;
private ImageView mExit;
private Spinner mSpinner;
private TextView mNext;
private ProgressBar mProgressBar;
private List<String> directories;
private GridView mGridView;
private ImageView mGalleryImage;
private HashMap<String, ArrayList<String>> directoryToImage;
private String append = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mExit = (ImageView) view.findViewById(R.id.exitShare);
mSpinner = (Spinner) view.findViewById(R.id.shareSpinner);
mNext = (TextView) view.findViewById(R.id.shareNext);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mGridView = (GridView) view.findViewById(R.id.gridView);
mGalleryImage = (ImageView) view.findViewById(R.id.galleryImageView);
mExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to next step in sharing photo");
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra("selected_image", mSelectedImage);
startActivity(intent);
}
});
init();
return view;
}
private void init() {
ImageFinder imageFinder = new ImageFinder();
imageFinder.getImages(getActivity());
directoryToImage = imageFinder.getImageMapping();
directories = new ArrayList<>(directoryToImage.keySet());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected: " + directories.get(position));
setUpGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setUpGridView(String directory) {
final ArrayList<String> imgURLS = directoryToImage.get(directory);
Log.d(TAG, "setUpGridView: Displaying " + directory + " with " + imgURLS.size() + " images");
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_COLUMNS;
Log.d(TAG, "setUpGridView: Image Width is " + imageWidth);
mGridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, append, imgURLS);
mGridView.setAdapter(adapter);
UniversalImageLoader.setImage(imgURLS.get(0),mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UniversalImageLoader.setImage(imgURLS.get(position), mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
}
});}
I display the images using a library called Universal Image loader
GridImageAdapter.java
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SquareImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridProgressBar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridViewImage);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
Log.d(TAG, "getView: Loading position " + position + ", displaying " + imgURL + ", with image " + holder.image);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
First time posting, so I apologize if there's anything wrong with this post.
Sorry for being so general and unclear in my post, I wasn't quite sure which portion of the code was the problem area. After looking over the code again, I noticed a stupid mistake. I set GridView's numColumns attribute to 5 in fragment_gallery.xml, but calculated the column width in GalleryFragment.java using private static final int NUM_COLUMNS = 4. I assume that this caused images to be displayed in a non-existent 5th column.

Not able to call the Fragment's function in its Adapter, Android App Development

I am making an android app in which when an image is clicked, then it blurs and shows play and other options on the top of it. I am using a external library (https://github.com/daimajia/AndroidViewHover) for this particular effects but my problem is generic in nature.
Problem Statement:-
I am handling click event on the play option shown by the Blur surface i.e hover_sample.xml in the adapter (TrendingAdapter.java) and i want to call function for playing youtube video (public void openWebView(TrendingData image)) that is in fragment (TrendingFragment.java). So, essentially i want to access function in the fragment from its adapter.
I have tried various method but its not working. Code sample is as following.
TrendingFragment.java:-
public class TrendingFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterCallback {
private GridView mGridView;
private TrendingAdapter mAdapter;
private String movieJson;
private String caption;
Activity MyActivity = getActivity();
public static TrendingFragment getInstance() {
TrendingFragment fragment = new TrendingFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate( R.layout.activity_trending_fragment, container, false );
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mGridView = (GridView) view.findViewById( R.id.grid );
mGridView.setOnItemClickListener( this );
mGridView.setDrawSelectorOnTop( true );
TrendingActivity activity = (TrendingActivity) getActivity();
movieJson = activity.getMovieJson();
caption = activity.getNewCaption();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new TrendingAdapter( getActivity(), 0, this);
mGridView.setAdapter(mAdapter);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(movieJson)
.build();
TrendingApiInterface trendingApiInterface = restAdapter.create( TrendingApiInterface.class );
trendingApiInterface.getStreams(new Callback<List<TrendingData>>() {
#Override
public void success(List<TrendingData> galleryImages, Response response) {
if (galleryImages == null || galleryImages.isEmpty() || !isAdded() )
return;
for (TrendingData image : galleryImages) {
mAdapter.add(image);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void failure(RetrofitError error) {
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TrendingData image = (TrendingData) parent.getItemAtPosition( position );
openWebView(image);
}
public void openWebView(TrendingData image) {
try {
Intent intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), Config.YOUTUBE_API_KEY, image.getImage());
startActivity(intent);
}//If Youtube app is not present then open in webview
catch (ActivityNotFoundException ex){
Toast.makeText(getActivity(), "Please wait for few minutes.Its Loading...", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), "Latest Youtube Player is missing on your device.Opening in WebView.Download it for better experience", Toast.LENGTH_LONG).show();
String complete_url="https://www.youtube.com/watch?v=";
Intent intent = new Intent(getActivity(), webView.class );
intent.putExtra( webView.EXTRA_IMAGE, complete_url+image.getImage());
intent.putExtra( webView.PREVIOUS_ACTIVITY, "TrendingActivity.class");
intent.putExtra(webView.EXTRA_CAPTION, image.getCaption());
intent.putExtra( webView.EXTRA_BG_IMAGE, image.getBgImage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//finish();
startActivity(intent);
}
}
#Override
public void onMethodCallback(AdapterView<?> parent, View view, int position, long id) {
TrendingData image = (TrendingData) parent.getItemAtPosition( position );
openWebView(image);
}
}
TrendingAdapter.java:-
public class TrendingAdapter extends ArrayAdapter {
TrendingFragment lfg;
TrendingData image;
private AdapterCallback mAdapterCallback;
public TrendingAdapter(Context context, int resource, AdapterCallback callback) {
super(context, resource);
this.mAdapterCallback = callback;
}
//hover image
private BlurLayout mSampleLayout ;
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
if( convertView == null ) {
holder = new ViewHolder();
convertView = LayoutInflater.from( getContext() ).inflate( R.layout.activity_trending_adapter, parent, false );
holder.image = (ImageView) convertView.findViewById( R.id.image );
holder.caption=(TextView) convertView.findViewById(R.id.textView);
//holder.progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
convertView.setTag(holder);
BlurLayout.setGlobalDefaultDuration(450);
mSampleLayout = (BlurLayout)convertView.findViewById(R.id.blur_layout);
final View hover = LayoutInflater.from(getContext()).inflate(R.layout.hover_sample, null);
holder.play = (ImageView)hover.findViewById(R.id.heart);
holder.playList = (ImageView)hover.findViewById(R.id.share);
hover.findViewById(R.id.heart).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YoYo.with(Techniques.Tada)
.duration(550)
.playOn(v);
}
});
hover.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YoYo.with(Techniques.Swing)
.duration(550)
.playOn(v);
}
});
mSampleLayout.setHoverView(hover);
mSampleLayout.setBlurDuration(550);
mSampleLayout.addChildAppearAnimator(hover, R.id.heart, Techniques.FlipInX, 550, 0);
mSampleLayout.addChildAppearAnimator(hover, R.id.share, Techniques.FlipInX, 550, 250);
mSampleLayout.addChildAppearAnimator(hover, R.id.more, Techniques.FlipInX, 550, 500);
mSampleLayout.addChildDisappearAnimator(hover, R.id.heart, Techniques.FlipOutX, 550, 500);
mSampleLayout.addChildDisappearAnimator(hover, R.id.share, Techniques.FlipOutX, 550, 250);
mSampleLayout.addChildDisappearAnimator(hover, R.id.more, Techniques.FlipOutX, 550, 0);
mSampleLayout.addChildAppearAnimator(hover, R.id.description, Techniques.FadeInUp);
mSampleLayout.addChildDisappearAnimator(hover, R.id.description, Techniques.FadeOutDown);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ViewHolder tmp = holder;
Picasso.with(getContext()).load(getItem(position).getThumbnail())
.placeholder(getContext().getResources().getDrawable(R.drawable.place)).
error(getContext().getResources().getDrawable(R.drawable.place)).
into(holder.image);
return convertView;
}
private class ViewHolder {
ImageView image;
ProgressBar progress;
TextView caption;
ImageView play;
ImageView playList;
}
}
hover_sample.xml:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/animation_area"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="match_parent">
<ImageView
android:layout_marginRight="20dp"
android:id="#+id/heart"
android:src="#drawable/heart"
android:layout_width="50dp"
android:layout_height="50dp" />
<ImageView
android:id="#+id/share"
android:layout_marginRight="20dp"
android:src="#drawable/share"
android:layout_width="50dp"
android:layout_height="50dp"/>
<ImageView
android:id="#+id/more"
android:src="#drawable/more"
android:layout_width="50dp"
android:layout_height="50dp"/>
</LinearLayout>
<TextView
android:id="#+id/description"
android:text="Parse PHP SDK"
android:layout_marginLeft="12dp"
android:textColor="#ffffff"
android:layout_marginBottom="12dp"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Please suggest how the same can be achieved. I have tried various way suggested in this form for similar question but without any success.
Use a callback method. Create an interface. Let your fragment implement it. Pass the callback to adapter in it's constructor. Adapter uses callback to call interface method from which you can call webview().
See How to create interface between fragment and adapter.
While calling any adapter's method from fragment, you can use adapter's instance but communication from adapter to fragment should be done with callbacks.
As suggested by cgr in above post, I created an interface to communicate between Fragment & it's Adapter. Follow link shared by cgr. It's awesome.
Interface definition:-
void onMethodCallback(String url, String caption, String bgImage);
Then, used the callback function in the adapter class as:-
mAdapterCallback.onMethodCallback(getItem(position).getImage(), getItem(position).getCaption(),getItem(position).getBgImage());
This resolved my problem. Now, I am successfully able to call any function in the adapter class from it's fragment class.

How can I implement a delete button in a ListView and delete from database?

I'm very new to android and I was given a prewritten app that I must improve. One thing I have to do is add a delete button to each item in a ListView.
Here is the XML for my ListView element:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<ImageView
android:id="#+id/li_map_image"
android:layout_width="50dp"
android:layout_height="match_parent"
android:contentDescription="thumbnail" />
<TextView
android:id="#+id/li_map_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:paddingLeft="8dp"
android:textSize="16sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/delete"
android:focusableInTouchMode="true"
android:background="#drawable/red_x"
android:layout_gravity="center|left"
android:onClick="deleteMap"></ImageButton>
Basically, I want the user to click the delete icon if they want to delete a row in the ListView. Also, this should delete the item's data from the database. I'm very confused about how to implement this because I don't know how I will know which delete button they are clicking. Also, when I added the ImageButton to the ListView code, it tells me to make the onClick method in main (should it be in main?); but how will I be able to delete data from the database? Also, Main Activity has a Fragment which obtains the ListView code. This is the Fragment class:
public class MapListFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int LOADER_ID = 1;
private static final String[] FROM = { Database.Maps.DATA,
Database.Maps.NAME };
private static final String[] CURSOR_COLUMNS = { Database.Maps.ID,
Database.Maps.DATA, Database.Maps.NAME };
private static final int[] TO = { R.id.li_map_image, R.id.li_map_name };
private SimpleCursorAdapter mAdapter;
// FIXME isn't this unnecessary?
public MapListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// FIXME reverse the order so the newest sessions are at the top
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.map_list_item, null, FROM, TO, 0);
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.li_map_image) {
((ImageView) view).setImageURI(Uri.parse(cursor
.getString(columnIndex)));
return true;
}
return false;
}
});
setListAdapter(mAdapter);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public void onListItemClick(ListView list, View v, int position, long id) {
final Intent nextIntent = new Intent(getActivity(),
ViewMapActivity.class);
nextIntent.putExtra(Utils.Constants.MAP_ID_EXTRA, id);
startActivity(nextIntent);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), DataProvider.MAPS_URI,
CURSOR_COLUMNS, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (loader.getId() == LOADER_ID)
mAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
I'm very lost as how to implement this delete feature. Any help will be much appreciated :)
here is a very good tutorial on how to put a clicklistener on a button inside listview.
follow this link
inside your adapter getView method, you need to put click listener on button like this
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.child_listview, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView
.findViewById(R.id.childTextView);
viewHolder.button = (Button) convertView
.findViewById(R.id.childButton);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position,temp);
}
}
});
return convertView;
}
Add Longclicklistner in Your Listview
try this , it may help you
Link

How to get path of checked picture using checkbox from grid view of photo Gallery in android

I am trying to get path of photo from gallery which in grid view. this gallery consists of each thumbnail with attached checkbox. Here is the whole code:
public class GridGallery extends Activity
{
ArrayList<String>list;
AlertDialog.Builder alert;
private Button send;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_gallery);
DataModel dbModel = new DataModel(this);
list = dbModel.selectAll();
alert = new AlertDialog.Builder(GridGallery.this);
send = (Button)findViewById(R.id.send_message);
gridView = (GridView) findViewById(R.id.sdcard);
gridView.setAdapter(new ImageAdapter(this));
gridView.setClickable(true);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos,
long id)
{
// TODO Auto-generated method stub
final int position = pos;
final String path = list.get(position).toString();
final String option[] = new String[]{"Send to","Watch"};
alert.setTitle("Pick options");
alert.setItems(option, new OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
if(option[which].equals("Watch"))
{
if(path.contains(".jpg"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "image/jpeg");
startActivity(intent);
}
else if(path.contains(".mp4"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "video/*");
startActivity(intent);
}
else
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "audio/*");
startActivity(intent);
}
}//
else
{
Intent sendMail = new Intent(GridGallery.this, SendMessage.class);
sendMail.putExtra("path", path);
startActivity(sendMail);
}
}
}).show();
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
// TODO Auto-generated method stub
String path = null;
Intent sendToMail = new Intent(GridGallery.this, SendMessage.class);
sendToMail.putExtra("path", path);
startActivity(sendToMail);
}
});
}
/**
* Adapter for our image files.
*/
private class ImageAdapter extends BaseAdapter
{
private final Context context;
Bitmap bitmap;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount()
{
return list.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView picturesView;
View myView = convertView;
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//getLayoutInflater();
myView = layoutInflater.inflate(R.layout.image_selection, null);
picturesView = new ImageView(context);
picturesView = (ImageView)myView.findViewById(R.id.item_grid);
picturesView.setClickable(true);
if(list.get(position).contains(".jpg"))
{
bitmap = BitmapFactory.decodeFile(list.get(position));
}
else if(list.get(position).contains(".mp4"))
{
bitmap = ThumbnailUtils.createVideoThumbnail(list.get(position), 0);
}
else
{
}
picturesView.setImageBitmap(bitmap);
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
return myView;
}
else
{
myView = convertView;
return myView;
}
}
}
}
MY problem is I can not be able to click the image or video thumbnail. also how do I able to get the image when I checked the check box.
here is XML code for Image_selection:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center_horizontal">
<ImageView android:id="#+id/item_grid" android:layout_width="100dip" android:layout_height="100dip"/>
<CheckBox android:id="#+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" />
and grid_gallery.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sdcard"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</RelativeLayout>
please help me. Thanks in advance
it seems you store the image path in the ArrayList list. If so, then set an onItemClickListeber for the GridView. in the onItemClick method you get the position of the gridview which was clicked. try 'list.get(position)in theonItemClick` to get the path

Categories

Resources