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;
}
}
Related
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
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();
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)
I am new to android development and am trying to workaround with some installed applications in my app. The problem is that am getting some casting error
(android.support.constraint.ConstraintLayout cannot be cast to android.widget.TextView)
I have referred to many posts here and i tried to figured out but no luck with that. As a last try I am posting my code here, hoping a response.
The entire code is posted below`.
Any help would be appreciated
ApplicationAdapter.java
package e.nani.myapplication;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo > {
private int resourceLayout;
private Context mContext;
List<ApplicationInfo> items;
PackageManager pm ;
ApplicationInfo p;
public ApplicationAdapter(Context context, int resource, List<ApplicationInfo> items) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_view, null);
}
pm=mContext.getPackageManager();
p = items.get(position);
if (p!= null) {
ImageView tt1 = (ImageView)view.findViewById(R.id.img);
TextView tt2= (TextView)view.findViewById(R.id.t1);
if (tt1 != null) {
tt1.setImageDrawable(p.loadIcon(pm));
}
if (tt2 != null) {
tt2.setText(p.packageName);
}
}
return view;
}
}
MainActivity.java
package e.nani.myapplication;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listview;
ApplicationAdapter<ApplicationInfo> adapter;
List<ApplicationInfo> ls=new ArrayList<>();
PackageManager pm;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.lists);
try {
pm= getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
ls.add(packageInfo);
adapter = new ApplicationAdapter<ApplicationInfo>(this, R.layout.row_view, ls);
listview.setAdapter(adapter);
Log.i("added", String.valueOf(pm.getClass().getName()));
Log.i("middle",packageInfo.packageName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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=".MainActivity">
<ListView
android:id="#+id/lists"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</android.widget.RelativeLayout>
row_view.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/t2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
``the crash report
Caused by: java.lang.ClassCastException: android.support.constraint.ConstraintLayout cannot be cast to android.widget.TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:432)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:415)
at e.nani.myapplication.ApplicationAdapter.getView(ApplicationAdapter.java:49)
at android.widget.AbsListView.obtainView(AbsListView.java:2408)
at android.widget.ListView.makeAndAddView(ListView.java:2126)
at android.widget.ListView.fillDown(ListView.java:851)
at android.widget.ListView.fillDown(ListView.java:833)
at android.widget.ListView.fillFromTop(ListView.java:921)
at android.widget.ListView.layoutChildren(ListView.java:1900)
at android.widget.AbsListView.onLayout(AbsListView.java:2207)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1083)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:754)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2991)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2504)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1635)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7795)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1172)
at android.view.Choreographer.doCallbacks(Choreographer.java:984)
at android.view.Choreographer.doFrame(Choreographer.java:809)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1158)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Try to use ViewHolder pattern:
static class ViewHolder {
ImageView tt1;
TextView tt2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_view, null);
holder = new ViewHolder();
holder.tt1 = (ImageView)view.findViewById(R.id.img);
holder.tt2 = (TextView)view.findViewById(R.id.t1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
pm = mContext.getPackageManager();
p = items.get(position);
if (p != null) {
holder.tt1.setImageDrawable(p.loadIcon(pm));
holder.tt2.setText(p.packageName);
}
return view;
}
Useful link:
https://stackoverflow.com/a/3832467/10995239
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.