RecyclerView onCreateViewHolder not being called - java

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.

Related

I can't select an item in list view

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();

Why My Recyclerview Isn't Working In An Acticvity

I need to parse json and show them on RecyclerView.. But my RecyclerView isn't working..
I need to fix this..
This is Json
Simple Json File for My app
[
{
"name": "Saif Maroof",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"StudentImage": "R.drawble.books"
},
{
"name": "Minhaj",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"studentimage": "R.drawble.books"
}
]
This is StudentInfo Activity
I think in this activity nothing gets wrong
package com.college.npc17_18.activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import com.college.npc17_18.MainActivity;
import com.college.npc17_18.R;
import com.college.npc17_18.adapter.StudentInfoAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class StudentInfo extends AppCompatActivity {
RecyclerView recyclerView;
StudentInfoAdapter studentInfoAdapter;
RecyclerView.Adapter adapter;
// ProgressBar progressBar;
RecyclerView.LayoutManager layoutManager;
List <Object> studentInfo = new ArrayList<>();
DividerItemDecoration dividerItemDecoration;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// progressBar = findViewById(R.id.progress_circular_country);
recyclerView = findViewById(R.id.studentsInfoRecycleView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new StudentInfoAdapter(this,studentInfo);
// String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "studentinfo.json");
// progressBar.setVisibility(View.GONE);
// studentInfoAdapter = new StudentInfoAdapter(this,studentInfo);
recyclerView.setAdapter(adapter);
addItemsFromJSON();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void addItemsFromJSON() {
try {
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject itemObj = jsonArray.getJSONObject(i);
String name = itemObj.getString("name");
String roll = itemObj.getString ("roll");
String phonenumber = itemObj.getString("phonenumber");
String gender = itemObj.getString("gender");
int studentimage = itemObj.getInt("studentimage");
com.college.npc17_18.model.StudentInfo studentInfos = new com.college.npc17_18.model.StudentInfo(name,roll,phonenumber,gender,studentimage);
studentInfo.add(studentInfos);
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: ", e);
}
}
private String readJSONDataFromFile() throws IOException{
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonString = null;
inputStream = getResources().openRawResource(R.raw.studentinfo);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonString = bufferedReader.readLine()) != null) {
builder.append(jsonString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is StudentInfo Adapter
package com.college.npc17_18.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.college.npc17_18.R;
import com.college.npc17_18.model.StudentInfo;
import java.util.ArrayList;
import java.util.List;
public class StudentInfoAdapter extends RecyclerView.Adapter <StudentInfoAdapter.Viewholder> {
private List <Object> studentInfos;
Context context;
public StudentInfoAdapter(Context context, List<Object> studentInfo) {
this.studentInfos = studentInfo;
this.context = context;
}
#NonNull
#Override
public StudentInfoAdapter.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.studentitem,parent,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentInfoAdapter.Viewholder holder, int position) {
StudentInfo studentInfo = (StudentInfo) studentInfos.get(position);
holder.StudentImageId.setImageResource (studentInfo.getStudentImage());
holder.NameId.setText("Name:"+studentInfo.getNamme());
holder.RollId.setText("Roll"+studentInfo.getRoll());
holder.GenderId.setText("Gender:"+studentInfo.getGender());
holder.PhoneNumberId.setText("Phone Number:"+studentInfo.getPhoneNumber());
}
#Override
public int getItemCount() {
return studentInfos.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
TextView NameId,RollId,PhoneNumberId,GenderId;
ImageView StudentImageId;
public Viewholder(#NonNull View itemView) {
super(itemView);
StudentImageId = itemView.findViewById(R.id.StudentImageId);
NameId = itemView.findViewById(R.id.NameId);
RollId = itemView.findViewById(R.id.RollId);
// CGPAId = itemView.findViewById(R.id.CGPAId);
GenderId = itemView.findViewById(R.id.GenderId);
PhoneNumberId = itemView.findViewById(R.id.PhoneNumberId);
}
}
}
This is StudentItem.xml
Layout for RecyclerView...
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:clickable="true"
android:elevation="40dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/StudentImageId"
android:layout_width="71dp"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/NameId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="18sp" />
<TextView
android:id="#+id/RollId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll" />
<TextView
android:id="#+id/GenderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gender" />
<TextView
android:id="#+id/PhoneNumberId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Number" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Now what do I need to do?
At the time when you instantiate an object of your adapter class
adapter = new StudentInfoAdapter(this,studentInfo);
Your adapter object is initialized with an empty studentInfo list
So, you should call adapter.notifyDataSetChanged(); in your addItemsFromJSON() method when the JSON parsing is completed.
update your adapter after you set your data
yourAdapter.notifyDataSerChanged();

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;
}
}

Fragment.java Error:(94, 51) error: incompatible types: NewsFragment cannot be converted to Context

Good day everyone, I am trying to figure out how to parse JSON and display with recyclerView and cardview. I do not understand why the fragment cannot be converted to context. Has anyone faced this error before?
The error starts from here:
gridLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(gridLayoutManager);
nAdapter = new newsAdapter(this,data_list);
Messages Gradle Build:
D:\New
folder\DrawerWithSwipeTabs\app\src\main\java\com\androidbelieve\drawerwithswipetabs\NewsFragment.java
Error:(94, 51) error: incompatible types: NewsFragment cannot be converted to Context
Error:(97, 36) error: incompatible types: NewsFragment cannot be converted to Context
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
NewsFragment.java
package com.androidbelieve.drawerwithswipetabs;
import android.app.LauncherActivity;
import android.graphics.Movie;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Ratan on 7/29/2015.
*/
public class NewsFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private GridLayoutManager gridLayoutManager;
private newsAdapter nAdapter;
private List<listnews> data_list;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.news_layout,container,false);
mRecyclerView =(RecyclerView)view.findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
data_list = new ArrayList<>();
load_data_from_server(0);
gridLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(gridLayoutManager);
nAdapter = new newsAdapter(this,data_list);
mRecyclerView.setAdapter(nAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(gridLayoutManager.findLastCompletelyVisibleItemPosition() == data_list.size()-1)
{
load_data_from_server(data_list.get(data_list.size()-1).getId());
}
}
});
return view;
}
private void load_data_from_server(final int id)
{
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.107.1/ibmcoe_la/selected.php?id="+id)
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for(int i=0; i<array.length(); i++)
{
JSONObject object = array.getJSONObject(i);
listnews data = new listnews(object.getInt("news_id"),object.getString("path_image")
,object.getString("news_title"),object.getString("news_image"),object.getString("news_description"));
data_list.add(data);
}
}catch (IOException e){
e.printStackTrace();
}catch (JSONException e){
System.out.println("End of content");
}
return null;
}
protected void onPostExecute(Void avoid){
nAdapter.notifyDataSetChanged();
}
};
task.execute(id);
}
#Override
public String toString()
{
return "NewsFragment";
}
}
newsAdapter.java
package com.androidbelieve.drawerwithswipetabs;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
/**
* Created by LENOVO on 20/2/2017.
*/
public class newsAdapter extends RecyclerView.Adapter<newsAdapter.ViewHolder> {
private Context context;
private List<listnews> my_data;
public newsAdapter(Context context, List<listnews> my_data)
{
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_news,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.description.setText(my_data.get(position).getImagedescription());
Glide.with(context).load(my_data.get(position).getImagepath()).into(holder.dataimage);
}
#Override
public int getItemCount() {
return 0;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView description;
public TextView imagetitle;
public ImageView dataimage;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.textView3);
imagetitle = (TextView) itemView.findViewById(R.id.textView4);
dataimage = (ImageView) itemView.findViewById(R.id.imageView4);
}
}
}
listnews.java
package com.androidbelieve.drawerwithswipetabs;
/**
* Created by LENOVO on 21/2/2017.
*/
public class listnews {
public int id;
public String imagedescription, image, imagepath, imagetitle;
public listnews(int id, String imagedescription, String image, String imagepath, String imagetitle) {
this.id = id;
this.imagedescription = imagedescription;
this.image = image;
this.imagepath = imagepath;
this.imagetitle = imagetitle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImagedescription() {
return imagedescription;
}
public void setImagedescription(String imagedescription) {
this.imagedescription = imagedescription;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public String getImagetitle() {
return imagetitle;
}
public void setImagetitle(String imagetitle) {
this.imagetitle = imagetitle;
}
}
recycle.news.xml (fragment 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"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="#+id/recyclerview"
android:clickable="true"
android:focusable="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
recycle_news.xml (cardview layout)
<android.support.v7.widget.CardView
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:android2="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="https://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android2:layout_marginTop="5dp"
android2:layout_marginLeft="5dp"
android2:layout_marginRight="5dp"
android2:layout_gravity="center|top"
card_view:cardPreventCornerOverlap="false"
card_view:cardCornerRadius="20dp"
android2:layout_width="match_parent"
android2:layout_height="wrap_content">
<FrameLayout
android2:layout_width="match_parent"
android2:layout_height="400dp"
app:cardElevation="0dp"
android2:background="#drawable/cardviewstring">
<LinearLayout
android2:orientation="vertical"
android2:layout_width="380dp"
android2:layout_height="match_parent"
android2:weightSum="1"
android2:layout_marginRight="20dp">
<LinearLayout
android2:orientation="vertical"
android2:layout_width="match_parent"
android2:layout_weight="1"
android2:layout_height="250dp">
<ImageView
android2:layout_width="match_parent"
android2:layout_height="match_parent"
app:srcCompat="#mipmap/ic_launcher"
android2:id="#+id/imageView4" />
</LinearLayout>
<LinearLayout
android2:orientation="vertical"
android2:layout_width="match_parent"
android2:layout_height="wrap_content"
android2:paddingTop="25dp">
<ScrollView
android2:layout_width="match_parent"
android2:layout_height="84dp"
android2:background="#drawable/screen_background_dark_transparent"
android2:layout_marginLeft="3dp">
<LinearLayout
android2:layout_width="match_parent"
android2:layout_height="wrap_content"
android2:orientation="vertical" >
<TextView
android2:text="TextView"
android2:layout_width="match_parent"
android2:layout_height="wrap_content"
android2:id="#+id/textView4" />
<TextView
android2:text="TextView"
android2:layout_width="match_parent"
android2:layout_height="35dp"
android2:id="#+id/textView3" />
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android2:orientation="vertical"
android2:layout_marginTop="10dp"
android2:layout_width="match_parent"
android2:layout_height="42dp"
android:layout_alignParentBottom="true">
<LinearLayout
android2:orientation="horizontal"
android2:layout_width="match_parent"
android2:layout_height="match_parent">
<ImageView
android2:layout_width="wrap_content"
android2:layout_height="wrap_content"
app:srcCompat="#drawable/ic_share"
android2:id="#+id/imageView3"
android2:layout_weight="1" />
<ImageView
android2:layout_width="wrap_content"
android2:layout_height="wrap_content"
app:srcCompat="#drawable/ic_like"
android2:id="#+id/imageView2"
android2:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
</android.support.v7.widget.CardView>
Use
gridLayoutManager = new GridLayoutManager(getActivity(),2);
mRecyclerView.setLayoutManager(gridLayoutManager);
instead of
gridLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(gridLayoutManager);
You can not use this for getting context inside a fragment.You will have to use getActivity() for getting the context from the parent activity of the fragment.
Your problem is this line -
gridLayoutManager = new GridLayoutManager(this, 2); // this refers to your current fragment
nAdapter = new newsAdapter(this,data_list); // same mistake
Basically, You can not use Fragment as a context. Instead you need to use Activity to which your Fragment is Attached. Get your activity via getActivity() method of Fragment.
I tell you the reason - Activity extends Context while Fragment does not.
Finally, the code will be,
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
nAdapter = new newsAdapter(getActivity(), data_list);

Categories

Resources