How can I integrate the RecyclerView with images in android? - java

I am trying to create the image gallery . I am using the recyclerview for the same as there can be large number of images. This is what I am trying to do :
When the user opens up the app android will ask for its permission for images (working)
After selecting either option add it to the image view present in the recyclerview (not working).
If image is saved how to re-render it back to the recyclerview (not working)
Here is what I am trying to do :
This is my Activity file named GalleryActivity.java :
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.traveloholic.R;
import com.traveloholic.models.Gallery;
import java.util.ArrayList;
public class GalleryActivity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.imagegallery);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
recyclerView.setLayoutManager(layoutManager);
Gallery galleryObj = this.getImage();
GalleryAdapter adapter = new GalleryAdapter(GalleryActivity.this, galleryObj);
recyclerView.setAdapter(adapter);
}
private Gallery getImage(){
Gallery galleryObj = new Gallery();
galleryObj.setImageUrl("");
galleryObj.setImageTitle(null);
return galleryObj;
}
public void getImage(ImageView img){
this.imageView = img;
this.selectImage(GalleryActivity.this);
}
private void selectImage(Context context) {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);//one can be replaced with any action code
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
this.imageView.setImageBitmap(selectedImage);
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
this.imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
}
break;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
Here is the layout file activity_galler.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".activities.GalleryActivity">
<TextView
android:id="#+id/gallery_screen_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/gallery_screen_message"
android:textSize="#dimen/page_identifier_textSize"
android:fontFamily="#font/sanfranciscodisplay_bold"
android:textColor="#color/colorPrimary"
android:layout_marginTop="#dimen/page_identifier_marginTop"
android:textAlignment="center"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"/>
<TextView
android:id="#+id/gallery_screen_submessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="11sp"
android:layout_below="#id/gallery_screen_message"
android:textColor="#color/black"
android:fontFamily="#font/sanfranciscodisplay_regular"
android:textAlignment="center"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/imagegallery"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/gallery_screen_submessage"
android:layout_marginBottom="85dp"
android:layout_marginTop="#dimen/activity_signup_first_marginTop">
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/continue_to_fourth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/custom_layout_first"
android:fontFamily="#font/sanfranciscodisplay_regular"
android:text="#string/continue_msg"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="18sp"
android:layout_alignParentBottom="true"
android:layout_marginStart="16dp"
android:layout_marginBottom="#dimen/activity_signup_marginBottom"
android:layout_marginEnd="16dp">
</Button>
</RelativeLayout>
Here is the Adapter class GalleryAdapter :
import android.app.Dialog;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import com.traveloholic.R;
import com.traveloholic.models.Gallery;
import java.io.File;
import java.util.ArrayList;
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
private Gallery galleryObj;
private Context context;
public GalleryAdapter(Context context, Gallery galleryObj) {
this.galleryObj = galleryObj;
this.context = context;
}
#Override
public GalleryAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.image_cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final GalleryAdapter.ViewHolder viewHolder, int i) {
viewHolder.img.setImageBitmap(BitmapFactory.decodeFile(galleryObj.getImageUrl()));
}
#Override
public int getItemCount() {
//return galleryList.size();
return 1;
}
public class ViewHolder extends RecyclerView.ViewHolder{
//private TextView title;
private ImageView img;
private ImageButton addRemoveButton;
public ViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.img);
addRemoveButton = (ImageButton) itemView.findViewById(R.id.add_remove_icon);
this.addOperationToAddButton();
}
private void addOperationToAddButton(){
addRemoveButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
GalleryActivity galleryActivity = (GalleryActivity)context;
galleryActivity.getImage(img);
}
}
);
}
}
}
Here is my another layout file image_cell_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/custom_layout_five"
android:layout_height="150dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:id="#+id/image_layout">
<ImageView
android:id="#+id/img"
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/photo_placeholder" />
<ImageButton
android:id="#+id/add_remove_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:src="#drawable/add_image" />
</RelativeLayout>
Can anyone help me with this how can I solve the three problems mentioned above . Any better aproach to do all this ??
Thanks

Related

Getting all launchable apps on home like android home menu with bottom dots

Hi i am working on a custom launcher app.I want to get all launchable apps on home like this.
My Current Code:
MainActivity.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycalview);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
StaggeredGridLayoutManager mGridLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL); // 2 is number of items per row
recyclerView.setLayoutManager(mGridLayoutManager); // deafult
PackageManager pm = this.getPackageManager();
Intent main = new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
Collections.sort(launchables,
new ResolveInfo.DisplayNameComparator(pm));
Adapter adapter = new Adapter(this, launchables, pm);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mGridLayoutManager);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycalview"
android:layout_below="#+id/battery"
android:layout_width="match_parent"
android:layout_above="#id/hi"
android:layout_height="match_parent" />
</RelativeLayout>
Adapter.java
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<ResolveInfo> lapps;
Context context;
PackageManager pm=null;
public Adapter(Context context, List<ResolveInfo> apps, PackageManager pn) {
this.context = context;
lapps=apps;
pm=pn;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.griditem, parent, false);
Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.images.setImageDrawable(lapps.get(position).loadIcon(pm));
holder.text.setText(lapps.get(position).loadLabel(pm));
holder.itemlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ResolveInfo launchable = lapps.get(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return lapps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView images;
TextView text;
RelativeLayout itemlayout;
public ViewHolder(View view) {
super(view);
images = (ImageView) view.findViewById(R.id.icon);
text = (TextView) view.findViewById(R.id.label);
itemlayout=view.findViewById(R.id.item);
}
}
}
griditem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/item"
android:layout_marginTop="5dp"
android:gravity="center"
android:layout_height="wrap_content">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/icon"
android:theme="#style/Theme.RoundedImage"/>
<TextView
android:layout_width="60dp"
android:layout_height="20dp"
android:layout_marginTop="5dp"
android:layout_below="#id/icon"
android:gravity="center_horizontal"
android:textSize="15dp"
android:textColor="#color/white"
android:textStyle="bold"
android:id="#+id/label"/>
</RelativeLayout>
I just want to show all apps on home screen with horizontal scroll with bottom dots.
I have also try this method but my issue can't solved

How to zoom out a bitmap image?

I'm capturing an image using a biometric reader.
Connecting the reader to the tablet and capturing the image works fine, but the image looks like this:
The image is cropped. It looks like it's magnified when the biometric capture takes place.
this is my code:
package mobfeel.com.br.exfingerprintreaderuareu4500;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import asia.kanopi.fingerscan.Status;
public class MainActivity extends AppCompatActivity {
private ImageView ivFingerprint;
private Button btScan;
private static final int SCAN_FINGERPRINT = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
btScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, SCAN_FINGERPRINT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case SCAN_FINGERPRINT:
if (resultCode == RESULT_OK) {
int status = data.getIntExtra("status", Status.ERROR);
if (status == Status.SUCCESS) {
toast("Fingerprint OK!");
byte[] img = data.getByteArrayExtra("img");
Bitmap bm = BitmapFactory.decodeByteArray(img, 0, img.length);
ivFingerprint.setImageBitmap(bm);
return;
}
toast(data.getStringExtra("errorMessage"));
}
break;
}
}
private void toast(String msg){
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
private void init(){
ivFingerprint = findViewById(R.id.ma_iv_fingerprint);
btScan = findViewById(R.id.ma_bt_scan);
}
}
And this is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<ImageView
android:id="#+id/ma_iv_fingerprint"
android:layout_width="221dp"
android:layout_height="206dp"
android:layout_gravity="center"
android:layout_marginBottom="460dp"
android:adjustViewBounds="true"
android:scaleType="fitXY"
app:layout_constraintBottom_toTopOf="#+id/ma_bt_scan"
app:srcCompat="#mipmap/ic_launcher"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="8dp" />
<Button
android:id="#+id/ma_bt_scan"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Scan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
I also have the ScanActivity.java class
package mobfeel.com.br.exfingerprintreaderuareu4500;
import android.content.Intent;
import android.os.Looper;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import asia.kanopi.fingerscan.Fingerprint;
import asia.kanopi.fingerscan.Status;
public class ScanActivity extends AppCompatActivity {
private TextView tvStatus;
private Fingerprint fingerprint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
init();
}
#Override
protected void onStart() {
fingerprint.scan(ScanActivity.this, printHandler, updateHandler);
super.onStart();
}
#Override
protected void onStop() {
fingerprint.turnOffReader();
super.onStop();
}
Handler updateHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
int status = msg.getData().getInt("status");
switch (status) {
case Status.INITIALISED:
tvStatus.setText("Setting up reader");
break;
case Status.SCANNER_POWERED_ON:
tvStatus.setText("Reader powered on");
break;
case Status.READY_TO_SCAN:
tvStatus.setText("Ready to scan finger");
break;
case Status.FINGER_DETECTED:
tvStatus.setText("Finger detected");
break;
case Status.RECEIVING_IMAGE:
tvStatus.setText("Receiving image");
break;
case Status.FINGER_LIFTED:
tvStatus.setText("Finger has been lifted off reader");
break;
case Status.SCANNER_POWERED_OFF:
tvStatus.setText("Reader is off");
break;
case Status.SUCCESS:
tvStatus.setText("Fingerprint successfully captured");
break;
case Status.ERROR:
tvStatus.setText("Error");
toast(msg.getData().getString("errorMessage"));
break;
default:
tvStatus.setText(String.valueOf(status));
toast(msg.getData().getString("errorMessage"));
break;
}
}
};
Handler printHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
byte[] image;
String errorMessage = "";
int status = msg.getData().getInt("status");
Intent intent = new Intent();
intent.putExtra("status", status);
if (status == Status.SUCCESS) {
intent.putExtra("img", msg.getData().getByteArray("img"));
} else {
intent.putExtra("errorMessage", msg.getData().getString("errorMessage"));
}
setResult(RESULT_OK, intent);
finish();
}
};
private void toast(String msg){
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
private void init() {
tvStatus = findViewById(R.id.sa_tv_status);
fingerprint = new Fingerprint();
}
}
activity_scan.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".ScanActivity">
<TextView
android:id="#+id/sa_tv_status"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
What feature can I use to zoom out?
I appreciate if anyone can help me analyze this!

Making buttons in recyclerview and cardview clickable

I've added buttons into a a cardview and recyclerview. I'm struggling to make the buttons clickable. Every time I click the buttons it's actually registering the recyclerview as being clicked.
Activity containing cardview and recyclerview
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.adapter.RecyclerAdapter;
import com.khumomashapa.notes.arraylists.Messages;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class StoreActivity extends AppCompatActivity {
// Widget
RecyclerView recyclerView;
//Firebase
private DatabaseReference mref;
// Variable
private ArrayList<Messages> messagesList;
private RecyclerAdapter recyclerAdapter;
private Context mContext;
Button PurchaseBtn;
Button DownloadBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store);
recyclerView = findViewById(R.id.products_view);
PurchaseBtn = (Button) findViewById(R.id.PurchaseBtn);
DownloadBtn = (Button) findViewById(R.id.DownloadBtn);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext()
,recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.ImageView);
Drawable mDrawable = imageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent intent = new Intent(view.getContext(),PreviewActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]bytes = stream.toByteArray();
intent.putExtra("image", bytes);
startActivity(intent);
Messages messages = messagesList.get(position);
Toast.makeText(StoreActivity.this, "You have selected: "+ messages.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
#Override
public void onButtonClicks(View view, int position) {
}
})
);
// Firebase
mref = FirebaseDatabase.getInstance().getReference();
// Arraylist
messagesList = new ArrayList<Messages>();
// Clear arraylist
ClearAll();
// Get data Method
GetDataFromFirebase();
}
private void GetDataFromFirebase(){
Query query = mref.child("Wallpapers");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Messages messages = new Messages();
messages.setImage(snapshot.child("image").getValue().toString());
messages.setTitle(snapshot.child("title").getValue().toString());
messagesList.add(messages);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), messagesList);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(messagesList != null){
messagesList.clear();
if (recyclerAdapter !=null){
recyclerAdapter.notifyDataSetChanged();
}
}
messagesList = new ArrayList<Messages>();
}
}
Recycler Adapter
package com.khumomashapa.notes.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.activities.StoreActivity;
import com.khumomashapa.notes.arraylists.Messages;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Messages> messagesList;
Button PurchaseBtn;
Button DownloadBtn;
View imageView;
public RecyclerAdapter(Context mContext, ArrayList<Messages> messagesArrayList) {
this.mContext = mContext;
this.messagesList = messagesArrayList;
View imageView;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Textview
holder.textView.setText(messagesList.get(position).getTitle());
holder.PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Imageview: Glide library
Glide.with(mContext)
.load(messagesList.get(position).getImage())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return messagesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
// Widgets;
ImageView imageView;
TextView textView;
Button PurchaseBtn;
Button DownloadBtn;
View v;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.ImageView);
textView = itemView.findViewById(R.id.Title);
PurchaseBtn = itemView.findViewById(R.id.PurchaseBtn);
DownloadBtn = itemView.findViewById(R.id.DownloadBtn);
View v;
}
}
}
Recycler Touch Listener
package com.khumomashapa.notes.activities
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
class RecyclerTouchListener(
context: Context?,
recyclerView: RecyclerView,
private val clickListener: ClickListener?
) :
OnItemTouchListener {
private val gestureDetector: GestureDetector
override fun onInterceptTouchEvent(recyclerView: RecyclerView, e: MotionEvent): Boolean {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recyclerView.getChildAdapterPosition(child))
}
return false
}
override fun onTouchEvent(recyclerView: RecyclerView, e: MotionEvent) {}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
interface ClickListener {
fun onClick(view: View?, position: Int)
fun onLongClick(view: View?, position: Int)
fun onButtonClicks(view: View?, position: Int)
}
init {
gestureDetector = GestureDetector(context, object : SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
override fun onLongPress(e: MotionEvent) {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child))
}
}
})
}
}
Cardview layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:contentPadding="5dp"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true"
app:cardElevation="3dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Imagelayout">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:padding="2dp"
android:id="#+id/ImageView"
android:contentDescription="#string/image" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Imagelayout">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title"
android:textColor="#color/textColor"
android:textSize="20sp"
android:fontFamily="#font/biorhyme_extralight"
android:id="#+id/Title"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/PurchaseBtn"
android:layout_width="350dp"
android:clickable="true"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:onClick="purchase"
android:text="#string/purchase"
android:layout_below="#+id/Title"
android:background="#drawable/btn_rounded"
android:textColor="#color/textColor"
android:textSize="12sp"
app:cornerRadius="20dp"
android:focusable="true" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/DownloadBtn"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_below="#+id/PurchaseBtn"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginTop="6dp"
android:background="#drawable/btn_rounded"
android:text="#string/download"
android:textColor="#color/textColor"
android:textSize="12sp"
android:visibility="invisible"
app:cornerRadius="20dp" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Recyclerview layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".activities.StoreActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/products_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout >
Another issue I know I'll encounter is the null reference exception.
How do I reference the buttons from the cardview layout when the content view is set to be shown from the other one.

listview onitemclicklistener not working using in activity

Hello friend i have custom listview using arrayadopter in my activity i am using listview on item click listner but problem is that its not working please help me here is my code the tost message which i used in my onitem click listner in my activity is not working what problem is here please tell
my custom layout for listview code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_margin="0dp"
android:padding="0dp"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="28dp"
android:layout_height="28dp"
android:id="#+id/versenumber"
android:text="1"
android:background="#drawable/roundedbutton"/>
<TextView
android:layout_width="match_parent"
android:id="#+id/verse"
android:layout_gravity="center|top"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#color/darkcolor"
android:textSize="20sp"
android:text="#string/versedisplay"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_gravity="top"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/speakverse"
android:layout_width="28dp"
android:layout_marginTop="10dp"
android:layout_height="28dp"
fab:srcCompat="#drawable/speak" />
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
android:id="#+id/share"
android:paddingTop="-10dp"
android:layout_marginTop="10dp"
android:src="#drawable/ic_share_black_24dp"/>
<ToggleButton
android:id="#+id/adbookmark"
android:layout_marginTop="10dp"
android:layout_width="27dp"
android:layout_height="28dp"
android:layout_gravity="right"
android:background="#drawable/toggle_selector"
android:textOff=""
android:textOn="" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:textAlignment="center"
android:layout_gravity="top"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".ALLVERSE">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorAccent"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/bookname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:textColor="#ffffff"
android:textStyle="bold"
android:text="ALL VERESE" />
</android.support.v7.widget.Toolbar>
<ListView
android:layout_below="#+id/toolbar"
android:id="#+id/mylistview"
android:divider="#null"
android:dividerHeight="3dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
tools:context=".ALLVERSE">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorAccent"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/allversecontent" />
</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/allverseappbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
package bible.swordof.God;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import es.dmoral.toasty.Toasty;
public class ALLVERSE extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ListView listView;
private ArrayList<String>versenumber;
private ArrayList<String>verselist;
private ArrayList<String>id;
private ArrayList<String>refernce;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
private String bookname;
private TextView booknametitle;
private FullverseAdopter adopter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allverse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
booknametitle=findViewById(R.id.bookname);
Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Boooknumber",0);
chapternumber= mIntent.getIntExtra("Chapternumber", 0);
bookname=mIntent.getStringExtra("Bookname");
booknametitle.setText(bookname.toString() +" "+ chapternumber);
//Toast.makeText(this, ""+bookname, Toast.LENGTH_SHORT).show();
setSupportActionBar(toolbar);
toolbar.setTitle("ALL VERSE");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
listView =findViewById(R.id.list);
adopter=new FullverseAdopter(this,R.layout.versedisplayrow,versenumber,verselist,refernce,id);
listView.setAdapter(adopter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ALLVERSE.this, "LIFE RUNS ON CODE", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void setData() {
versenumber=new ArrayList<>();
verselist=new ArrayList<>();
refernce=new ArrayList<>();
id=new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{ if (cursor.moveToFirst())
{
do {
id.add(cursor.getString(0));
versenumber.add(cursor.getString(1));
verselist.add(cursor.getString(2));
refernce.add(bookname+" "+chapternumber);
}
while (cursor.moveToNext());
}
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite)
{ Intent intent=new Intent(this,Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My adopter customadopter class:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean ischeckd;
String My_PREF="MY_PREF";
public String ex="switch";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//verselist highlight
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public void opecolorpicker(){
ColorPicker colorPicker = new ColorPicker(activity);
ArrayList<String>colors=new ArrayList<>();
colors.add("#FF0000");
colors.add("#FFEC33");
colors.add("#3C33FF");
colors.add("#DA33FF");
colors.add("#33FF99");
colors.add("#90FF33");
colors.add("#DD33FF");
colors.add("#F0B27A");
colors.add("#DAF7A6");
colors.add("#34495E");
colorPicker.setColors(colors).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
Toast.makeText(activity, ""+color, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
}
}).show();
}
}
Use this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(ALLVERSE.this, "LIFE RUNS ON CODE", Toast.LENGTH_SHORT).show();
}
});
Instead of:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ALLVERSE.this, "LIFE RUNS ON CODE", Toast.LENGTH_SHORT).show();
}
});

Android: How to create a filtering function with Checkbox

I am trying to create a filtering function with checkbox for my application. I have populated a list of installed application and i want to filter out only a few it. My idea is to get those checkbox that are checked and store it into an array. After which, display it back into a listview.
Example:
For this example, i would like to only list out Maps and Camera upon clicking on the submit button.
Does anyone know what should i do to achieve this? I'm clueless at the moment due to my knowledge of android studio.
Here is my code.
activity_main.xml
<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">
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
activity_list_app.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop"
android:contentDescription="#null"/>
<LinearLayout
android:layout_width="240dp"
android:layout_height="wrap_content"
android:gravity="center|center_vertical"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/app_name"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="left" />
<TextView
android:id="#+id/app_package"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="left" />
</LinearLayout>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkbox" />
MainActivity.java
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.CheckedTextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity{
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private AppAdapter listadapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
//ListView listview= getListView();
new LoadApplications().execute();
}
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try{
Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);
if(intent != null){
startActivity(intent);
}
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list){
ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
for(ApplicationInfo info : list){
try{
if(packageManager.getLaunchIntentForPackage(info.packageName)!=null){
appList.add(info);
}
}catch(Exception e){
e.printStackTrace();
}
}
return appList;
}
private class LoadApplications extends AsyncTask<Void, Void, Void>{
private ProgressDialog progress = null;
protected Void doInBackground(Void... params){
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadapter = new AppAdapter(MainActivity.this, R.layout.activity_list_app, applist);
return null;
}
protected void onPostExecute(Void result){
setListAdapter(listadapter);
progress.dismiss();
super.onPostExecute(result);
}
protected void onPreExecute(){
progress = ProgressDialog.show(MainActivity.this, null, "Loading apps info...");
super.onPreExecute();
}
}
}
AppAdapter.java
import java.util.List;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AppAdapter extends ArrayAdapter<ApplicationInfo>{
private List<ApplicationInfo> appList;
private Context context;
private PackageManager packageManager;
public AppAdapter(Context context, int resource, List<ApplicationInfo> objects){
super(context, resource,objects);
this.context = context;
this.appList= objects;
packageManager= context.getPackageManager();
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
if(null == view){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.activity_list_app,null);
}
ApplicationInfo data = appList.get(position);
if(null != data){
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_package);
ImageView iconView = (ImageView) view.findViewById(R.id.app_icon);
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconView.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
public int getCount(){
return((null != appList) ? appList.size() : 0);
}
public ApplicationInfo getItem(int position){
return((null != appList) ? appList.get(position): null);
}
public long getItemId(int position) {
return position;
}
}

Categories

Resources