Unable to display data in recycler view from room db - java

Getting error at NewActivity, as getting error while adding the data in array list and loading it to recycler view. Iam working on a project where I have to load Room data in recycler view. I am getting an error in for loop .. tried using foreach still getting tge same error. Error is showing while using add method to load a data from list to arraylist
package com.app.mycontacts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import com.app.mycontacts.AddContactActivity.AddContactActivity;
import com.app.mycontacts.Data.ContactDetails;
import com.app.mycontacts.Data.ContactRepository;
import com.app.mycontacts.Data.MyAdapterClass;
import com.app.mycontacts.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class NewActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<ContactDetails> contactarrayList;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= findViewById(R.id.reyclerview);
new LoadDataTask().execute();
}
class LoadDataTask extends AsyncTask<Void,Void,Void> {
ContactRepository contactRepository;
List<ContactDetails> contactList1;
#Override
protected void onPreExecute() {
super.onPreExecute();
contactRepository = new ContactRepository(getApplicationContext());
}
#Override
protected Void doInBackground(Void... voids) {
contactList1=contactRepository.getContactsDetails();
contactarrayList= new ArrayList<ContactDetails>();
for(int i=0; i<=contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
recyclerView.setLayoutManager(new LinearLayoutManager(NewActivity.this));
MyAdapterClass myAdapterClass= new MyAdapterClass(NewActivity.this,contactarrayList);
recyclerView.setAdapter(myAdapterClass);
}
}
}
Tried debugging the code, app is getting crash at the above stage.. Expecting to display the data inserted at room db.

You are indexing wrong in the loop.
The size of the list is 4 but Java indexes from 0. So if you have 4 elements it goes [0], [1], [2], [3]
for(int i=0; i<=contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
What you are doing is reaching for the fifth element - [0], [1], [2], [3], [4].
This will work:
for(int i=0; i < contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
But you don't need to iterate it, you should be able to just call .addAll.
contactarrayList.addAll(contactList1);

Related

Images not showing in recyclerview

I've spent som time trying to fix it, but my app works fine except for the images that don't load into my recyclerview. I tried with and without firebase database to get the images but in both case i don't get them.
However i get all my texts so i don't understand where the problem comes from. I searched for quite a time and didn't see anything that i didn't do in other tutorials/helps.
In my logcat i get the following errors :
2021-05-27 20:31:25.445 22716-22716/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2021-05-27 20:31:25.447 22716-22716/? E/Zygote: accessInfo : 1
And in the case of firebase Database i get the previous errors plus this one :
E/RecyclerView: No adapter attached; skipping layout
I put here my code so you can check if you need
Activity class :
package fr.balizok.pizzaapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import fr.balizok.pizzaapplication.adapter.PizzaAdapter;
public class MainActivity extends AppCompatActivity {
List<PizzaModel> pizzaList = new ArrayList<PizzaModel>();
RecyclerView recyclerViewPizzas;
PizzaAdapter pizzaAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizzaList.add(new PizzaModel(
"Margherita",
"Sauce tomate, Mozarella",
"5.80€",
"https://cdn.pixabay.com/photo/2020/06/08/16/49/pizza-5275191_960_720.jpg"));
pizzaList.add(new PizzaModel(
"Savoyarde",
"Sauce tomate, Mozarella, Pomme de terre, Fromage",
"10.20€",
"https://cdn.pixabay.com/photo/2017/11/23/16/57/pizza-2973200_960_720.jpg"));
pizzaList.add(new PizzaModel(
"Poulet pesto",
"Sauce tomate, Mozarella, Poulet, Pesto",
"8.50€",
"https://cdn.pixabay.com/photo/2016/06/08/00/03/pizza-1442945_960_720.jpg"));
pizzaList.add(new PizzaModel(
"4 Saisons",
"Sauce tomate, Mozarella, Olive, Basilic, Jambon, Champignons, Artichaut",
"9.60€",
"https://cdn.pixabay.com/photo/2016/06/08/00/03/pizza-1442946_960_720.jpg"));
recyclerViewPizzas = findViewById(R.id.recyclerViewPizzas);
recyclerViewPizzas.setHasFixedSize(true);
recyclerViewPizzas.setLayoutManager(new LinearLayoutManager(this));
pizzaAdapter = new PizzaAdapter(MainActivity.this, pizzaList);
recyclerViewPizzas.setAdapter(pizzaAdapter);
recyclerViewPizzas.addItemDecoration(new PizzaItemDecoration());
}
}
Adapter class :
package fr.balizok.pizzaapplication.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.bumptech.glide.Glide;
import java.util.List;
import fr.balizok.pizzaapplication.PizzaModel;
import fr.balizok.pizzaapplication.R;
public class PizzaAdapter extends RecyclerView.Adapter<PizzaAdapter.ViewHolder>{
Context context;
List<PizzaModel> pizzaList;
public PizzaAdapter(Context context, List<PizzaModel> pizzaList) {
this.context = context;
this.pizzaList = pizzaList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.menu_pizza_design,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PizzaAdapter.ViewHolder holder, int position) {
PizzaModel currentPizza = pizzaList.get(position);
holder.pizza_name.setText(currentPizza.getName());
holder.ingredients.setText(currentPizza.getIngredients());
holder.price.setText(currentPizza.getPrice());
Glide.with(context).load(currentPizza.getImageURL()).into(holder.pizza_image);
}
#Override
public int getItemCount() {
return pizzaList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView pizza_image;
TextView pizza_name, ingredients, price;
public ViewHolder(#NonNull View itemView) {
super(itemView);
pizza_image = itemView.findViewById(R.id.pizza_image);
pizza_name = itemView.findViewById(R.id.pizza_name);
ingredients = itemView.findViewById(R.id.ingredients);
price = itemView.findViewById(R.id.price);
}
}
}
Hope you can help me, thank you in advance !
I follow your code and make it demo its resolved by using Picasso library.
Try this one I hope it would be helpful to you.
Picasso.get()
.load(currentPizza.getImageURL())
.resize(600, 200) // resizes the image to these dimensions (in pixel) if you want
.centerInside()
.into(holder.pizza_image);

I m doing barcode scanner. But I can display my resultCode in textview.

I want to display the scan result from ZXING. I integrated ZXING into my android app, the scan works ok. Now I want to display the barcode number result in textview. I'm using zxing library in my project. I set up result.setText(resultCode) but it's not works. so this is code i m'follow from the tutorial.
package com.example.norhanom.barcodeqrcode;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; //view button or textfield
import android.widget.Toast; //to show and create message for user,appears
as floating view over app
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.google.zxing.Result;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AppCompatActivity {
private ZXingScannerView scannerView;
TextView result;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
}
public void scanCode(View view){
scannerView = new ZXingScannerView(this); // Programmatically initialize
the scanner view
scannerView.setResultHandler(new ZXingScannerResultHandler());
setContentView(scannerView); //Set the scanner view as the content view
scannerView.startCamera(); //scannerView open camera
}
#Override
public void onPause()
{
super.onPause();
scannerView.stopCamera(); //stop camera on pause
}
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler
{
#Override
public void handleResult(Result result1)
{
String resultCode = result1.getText(); //get the result
Toast.makeText(MainActivity.this,resultCode,Toast.LENGTH_LONG).show();
//show result
setContentView(R.layout.activity_main);
scannerView.stopCamera(); //camera stop
}
}
}
After using setContentView the next time, you should reassign the views.
//inside handleResult
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
result.setText(resultCode);
scannerView.stopCamera();

Disable screenshots in React Native

I know that you can not 100% stop the user from taking a screenshot if he insists to. But I read that you can still stop manual screenshots by setting LayoutParams.FLAG_SECURE in Java.
I tried adding it to my MainApplication file but getWindow() kept on throwing errors no matter what I do. So I moved that line of code to the MainActivity file and it worked without any errors.
Problem is, I can still normally take screenshots.
MainApplication:
package com.testapp;
import android.app.Activity;
import com.reactnativenavigation.NavigationApplication;
import com.facebook.react.modules.i18nmanager.I18nUtil;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import android.support.annotation.Nullable;
/* custom modules */
import com.oblador.vectoricons.VectorIconsPackage;
import org.pgsqlite.SQLitePluginPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends NavigationApplication {
#Override
public boolean isDebug() {
return BuildConfig.DEBUG;
}
#Nullable
#Override
public List<ReactPackage> createAdditionalReactPackages() {
return Arrays.<ReactPackage>asList(
new SQLitePluginPackage(),
new VectorIconsPackage(),
new RNDeviceInfo()
);
}
#Override
public void onCreate() {
super.onCreate();
I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance();
sharedI18nUtilInstance.allowRTL(getApplicationContext(), false);
}
}
MainActivity:
package com.testapp;
import android.widget.ImageView;
import com.reactnativenavigation.controllers.SplashActivity;
import android.os.Bundle;
import android.view.WindowManager.LayoutParams;
public class MainActivity extends SplashActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
}
}
I did simply the following and it is working properly:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_main);
}
}

Unable to get list items correct code using Java

I am trying to create a list view in Java that allows each list item to open a web url address but I can not seem to get the code right. Please can some one show me where IO going wrong.
package com.sasquatchapps.hydraquip10.bestofmonsterquest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Season1Activity extends Activity{
private String episodes[] = {"America's Loch Ness Monster","Sasquatch Attack",
"Giant Squid Found","Birdzilla","Bigfoot","“Mutant K9","Lions in the Backyard","Gigantic Killer Fish","Swamp Beast","Russia's Killer Apemen","Unidentified Flying Creatures","The Real Hobbit",
"Giganto: The Real King Kong","American Werewolf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, episodes);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "Item clicked;" + episodes[position], Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=o7-RdxrCFAg"));
startActivity(intent);
}
}
}
You have some errors - Where is your listview? Modify your code
1) create listview -
ListView myList;
2) In your onCreate assign this list:
myList = (ListView) findViewById(R.id.my_list);
3) Set adapter to your list:
myList.setAdapter(adapter);

Simple adapter not loading all the images

I'm using this code to show images from url in list view so im using this class that extended from simpleAdapter
package com.mypackage.lebadagency;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
// TODO Auto-generated constructor stub
}
#Override
public void setViewImage(ImageView v, String value) {
UrlImageViewHelper.setUrlDrawable(v, value);
}
}
and using it is like :
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new MyAdapter(
EconomyPanel.this, contactList,
R.layout.economy_list_item, new String[] {TAG_ID, TAG_IMAGE_URL,TAG_NAME
}, new int[] {R.id.idTV, R.id.image1,
R.id.name });
setListAdapter(adapter);
}
my list load 10 items, my problem is that it does not load all the 10 images , sometimes it only loads one of them , what is the problem and how to fix it ??
The problem is not with this code , this code is working no need to change the method of viewing the image or anything the problem is simpler than that , any image that contain space gab in its file name , the browsers can handle it by replacing the space with %20 , and when android retrieve the image url it retrieve it without the 20% symbol , so i need to add this command to the url :
value=value.replaceAll(" ", "%20");
and then
UrlImageViewHelper.setUrlDrawable(v, value);

Categories