I can't select an item in list view - java

I have searched various sites and tutorials and I've done exactly the same, but I can't even make a Toast from my list.
Here's my xml of my activity view list_view.xml:
<?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"
android:padding="50px"
android:background="#drawable/minimalist_wallpapers_droidviews_25"
tools:context=".ViewList"
>
<com.google.android.material.card.MaterialCardView
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/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/lista"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
Here's my ViewList.java:
package com.example.trialandroid;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.arcu.dao.DaoPersona;
import com.arcu.util.Adaptador;
import java.util.List;
public class ViewList extends AppCompatActivity {
DaoPersona dao;
Adaptador adaptador;
List lista;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
dao = new DaoPersona(ViewList.this);
lista = dao.listarPersonas();
adaptador = new Adaptador(lista, dao, this);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adaptador);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("onclicklistener");
Toast.makeText(getApplicationContext(), "Posicion: ", Toast.LENGTH_LONG);
}
});
}
}
And I also have an adapter class called Adaptador.java
package com.arcu.util;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.arcu.bean.BeanPersona;
import com.arcu.dao.DaoPersona;
import com.example.trialandroid.R;
import java.util.ArrayList;
import java.util.List;
public class Adaptador extends BaseAdapter {
List<BeanPersona> lista;
DaoPersona dao;
BeanPersona bean;
ConversorImagenes conversor = new ConversorImagenes();
Activity actividad;
public Adaptador(List<BeanPersona> lista, DaoPersona dao, Activity actividad) {
this.lista = lista;
this.dao = dao;
this.actividad = actividad;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public BeanPersona getItem(int i) {
bean = lista.get(i);
return null;
}
#Override
public long getItemId(int i) {
bean = lista.get(i);
return bean.getIdPersona();
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View vista = view;
if(vista == null){
LayoutInflater li = (LayoutInflater) actividad.getSystemService(ContextThemeWrapper.LAYOUT_INFLATER_SERVICE);
vista = li.inflate(R.layout.list_element,null);
}
bean = lista.get(position);
ImageView fotoLista = (ImageView) vista.findViewById(R.id.listFoto);
TextView nombreLista = (TextView) vista.findViewById(R.id.listNombre);
TextView fechaNacLista = (TextView) vista.findViewById(R.id.listFechaNac);
TextView areaTrabajoLista = (TextView) vista.findViewById(R.id.listAreaTrabajo);
Button modificarBtn = (Button) vista.findViewById(R.id.listBtnModificar);
Button eliminarBtn = (Button) vista.findViewById(R.id.listBtnEliminar);
fotoLista.setImageBitmap(conversor.stringABitmap(bean.getFoto()));
nombreLista.setText(bean.getNombre());
fechaNacLista.setText(bean.getFechaNac());
areaTrabajoLista.setText(bean.getAreaTrabajo());
modificarBtn.setTag(position);
eliminarBtn.setTag(position);
modificarBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
eliminarBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return vista;
}
}
I have no idea what's going on since I'm just starting in Android development.
Help please!
Thanks in advance.

you forgot to add .show() to your Toast. try this:
Toast.makeText(getApplicationContext(), "Posicion: ", Toast.LENGTH_LONG).show();

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

ListView with custom adapter is crashing after adding a new item? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Custom ListView Adapter Null Object Reference
(1 answer)
Closed 2 years ago.
I'm creating an app that makes inventaries for the restaurant of my parents. I've been working in the custom view that shows the name of the product and the quantity of it on the current inventary in a listView. Everything works fine until I add a new product to any inventary. After I add the product any time that I go to the that inventary the app crash.
This is visionInventario.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class visionInventario extends AppCompatActivity {
TextView tituloInventario;
static int positionCurrentInventario;
static InventarioListAdapter adapter1;
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list",null);
Type type = new TypeToken<ArrayList<Inventario>>(){}.getType();
Inventarios.InventariosActuales = gson.fromJson(json,type);
for(int i = 0; i < Inventarios.InventariosActuales.size();i++){
Inventarios.nombresInventarios.add(Inventarios.InventariosActuales.get(i).nombre);
}
if(Inventarios.InventariosActuales == null){
Inventarios.InventariosActuales = new ArrayList<>();
}
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(Inventarios.InventariosActuales);
editor.putString("task list",json);
editor.apply();
}
public void addProductoButton(View view){
Intent goToAddNewProducto = new Intent(this,addNewProducto.class);
startActivity(goToAddNewProducto);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vision_inventario);
//loadData();
tituloInventario = (TextView) findViewById(R.id.tituloInventario);
Intent thisIntent = getIntent();
positionCurrentInventario = thisIntent.getIntExtra("itemPosition",0);
tituloInventario.setText(Inventarios.nombresInventarios.get(positionCurrentInventario));
ListView listProductos = (ListView) findViewById(R.id.listaProductos);
adapter1 = new InventarioListAdapter(this,Inventarios.InventariosActuales.get(positionCurrentInventario).products);
listProductos.setAdapter(adapter1);
listProductos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent goToVisionProducto = new Intent(getApplicationContext(),visionProducto.class);
goToVisionProducto.putExtra("productPosition",position);
startActivity(goToVisionProducto);
}
});
}
}
This is addNewProducto.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
public class addNewProducto extends AppCompatActivity {
TextView nombreDelNuevoProducto;
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(Inventarios.InventariosActuales);
editor.putString("task list",json);
editor.apply();
}
public void AddNewProductoClick(View view){
producto nuevoProducto = new producto(nombreDelNuevoProducto.getText().toString());
Inventarios.InventariosActuales.get(visionInventario.positionCurrentInventario).addProduct(nuevoProducto);
visionInventario.adapter1.notifyDataSetChanged();
Toast.makeText(this,"¡Producto añadido!", Toast.LENGTH_SHORT).show();
saveData();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_producto);
nombreDelNuevoProducto = (TextView) findViewById(R.id.nombreProducto);
}
}
This is InventarioListAdapter.java
package com.DreamFactory.restaurantcontrol;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class InventarioListAdapter extends BaseAdapter {
Context context;
ArrayList<producto> arr;
public InventarioListAdapter(Context context, ArrayList<producto> arr) {
this.context = context;
this.arr = arr;
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(context).inflate(R.layout.adapter_view_layout, parent, false);
}
TextView quantity = (TextView)convertView.findViewById(R.id.existenciasInventarioVision);
TextView nameQ = (TextView) convertView.findViewById(R.id.productoInventarioVision);
quantity.setText(arr.get(position).cantidad);
nameQ.setText(arr.get(position).nombre);
return listItemView;
}
}
This is adapter_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<LinearLayout
android:layout_width="409dp"
android:layout_height="729dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/productoInventarioVision"
android:gravity="center"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="66.6"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="33.3"
android:orientation="vertical">
<TextView
android:id="#+id/existenciasInventarioVision"
android:layout_width="match_parent"
android:layout_height="61dp"
android:gravity="center"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstrainLayout>
This is my LogCat when it crashes
2020-04-05 22:49:14.310 17301-17301/com.DreamFactory.restaurantcontrol E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.DreamFactory.restaurantcontrol, PID: 17301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.DreamFactory.restaurantcontrol.InventarioListAdapter.getView(InventarioListAdapter.java:52)

How to Save İmage from ViewPager?

My problem is that it always saves the same photo when I press the Save Button. I have more than 10 photos in my Viewpager, it just saves the first one, so I can't save what I want the photo,
I want to save the open photo.
I want the photo in the open window to be saved.
items.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"
android:id="#+id/gallery_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/layut"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:orientation="vertical"
android:weightSum="30">
<FrameLayout
android:id="#+id/wallpaper_preview_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/movie_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</RelativeLayout>
fragment_simple.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=".Fragment.SimpleFragment">
<androidx.viewpager.widget.ViewPager
android:id="#+id/vivi_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/bSave"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:gravity="center"
android:layout_marginTop="150dp"
android:text="Save"
android:layout_alignParentStart="true"
android:textSize="24sp"
android:padding="0dp" />
</RelativeLayout>
SimpleFragment.java
package com.example.duvarlar.Fragment;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.duvarlar.Adapters.MyAdapter;
import com.example.duvarlar.Listeneer.IFirebaseLoadDone;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.example.duvarlar.Transformer.DeptPageTransformer;
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.ValueEventListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A simple {#link Fragment} subclass.
*/
public class SimpleFragment extends Fragment implements IFirebaseLoadDone, ValueEventListener {
ViewPager viewPager;
MyAdapter adapter;
DatabaseReference movies;
IFirebaseLoadDone iFirebaseLoadDone;
Button save;
OutputStream outputStream;
public SimpleFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_simple, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
iFirebaseLoadDone = this;
loadMovie();
viewPager = (ViewPager) view.findViewById(R.id.vivi_pager);
save = (Button) view.findViewById(R.id.bSave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setDrawingCacheEnabled(true);
Bitmap bitmap = viewPager.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Android");//directory name of your choice
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-" + n + ".jpg";
File file = new File(newDir, fotoname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Saved to your folder" + fotoname, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
adapter = new MyAdapter(getContext(), movieList);
viewPager.setAdapter(adapter);
}
#Override
public void onFirebasLoadFailed(String message) {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<Movie> movieList = new ArrayList<>();
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
MyAdapter.java
package com.example.duvarlar.Adapters;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
public class MyAdapter extends PagerAdapter {
Context context;
List<Movie> movieList;
LayoutInflater inflater;
OutputStream outputStream;
public MyAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
((ViewPager)container).removeView((View)object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
final View view = inflater.inflate(R.layout.items,container,false);
final ImageView movie_image = (ImageView)view.findViewById(R.id.movie_image);
Picasso.get()
.load(movieList.get(position).getImage())
.fit()
.centerCrop()
.into(movie_image);
container.addView(view);
return view;
}
}

RecyclerView onCreateViewHolder not being called

i want to add data inside RecyclerView.After done compiled, RecyclerView not showed inside virtual mobile.When i check again,onCreateViewHolder is not being called.Hope you guys can help me solve this problem.
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="com.example.user.mycustomvolley.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/recyclerview"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
row_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:background="#BBDEFB"
>
<com.android.volley.toolbox.NetworkImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_margin="8dp"
android:id="#+id/networkImage"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textName"
android:text="#string/title"
android:layout_toRightOf="#+id/networkImage"
android:padding="8dp"
android:textColor="#color/colorText"
android:textSize="18dp"
android:textStyle="bold"/>
</RelativeLayout>
MainActivity.java
package com.example.user.mycustomvolley;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<ArtInformation> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
BackgroundTask backgroundTask = new BackgroundTask(MainActivity.this);
arrayList = backgroundTask.getArrayList();
adapter = new RecyclerAdapter(arrayList,this);
recyclerView.setAdapter(adapter);
}
}
BackgroundTask.java
package com.example.user.mycustomvolley;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by User on 9/17/2016.
*/
public class BackgroundTask {
Context context;
ArrayList<ArtInformation> arrayList = new ArrayList<>();
private static final String json_url = "http://192.168.1.7/volley/imagetext/getData.php";
public BackgroundTask(Context context){
this.context = context;
}
public ArrayList<ArtInformation> getArrayList(){
//make json request.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,json_url,(String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try{
JSONObject jsonObject = response.getJSONObject(count);
String artTemp = jsonObject.getString("art");
String imageTemp = jsonObject.getString("image");
ArtInformation artInformation = new ArtInformation(artTemp,imageTemp);
arrayList.add(artInformation);
count++;
}catch (JSONException ex){
ex.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error:[JSON Process",Toast.LENGTH_LONG).show();
//progressDialog.hide();
error.printStackTrace();
}
});
MySingleton.getmInstances(context).addToRequestQueue(jsonArrayRequest);
return arrayList;
}
}
RecyclerAdapter.java
package com.example.user.mycustomvolley;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 9/17/2016.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<ArtInformation> arrayList = new ArrayList<>();
Context context;
private ImageLoader imageLoader;
public RecyclerAdapter(ArrayList<ArtInformation> list, Context context){
super();
this.arrayList = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("","call onCreateViewHolder");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_list,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ArtInformation artInformation = arrayList.get(position);
// Log.d("Check:","art:"+artInformation.getArt_name()+" / path:"+artInformation.getImage_path());
imageLoader = MySingleton.getmInstances(context).getImageLoader();
imageLoader.get(artInformation.getImage_path(), ImageLoader.getImageListener(holder.image, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.image.setImageUrl(artInformation.getImage_path(),imageLoader);
holder.artName.setText(artInformation.getArt_name());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView artName;
NetworkImageView image;
public MyViewHolder(View itemView){
super(itemView);
artName = (TextView) itemView.findViewById(R.id.textName);
image = (NetworkImageView) itemView.findViewById(R.id.networkImage);
}
}
}
If getItemCount method returns 0 i.e arrayList.size() == 0 then RecyclerView never tries to instantiate a view.

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