Problem pulling server list on Android

Asked

Viewed 53 times

2

Whoa, guys, I’m pulling a list from the server and populating a RecyclerView with that list. But when the list is empty, I want a message like: "There are no entries for that product yet". But not a Toast, and yes a fixed message in a TextView. Can someone help me?

Thanks

public class ProductAdminActivity extends AppCompatActivity {

public static final String APP_NAME = "PanApp";
public static final String URL = "https://panapp-backend.appspot.com/_ah/api";
private RecyclerView rvProductAdmin;
private Button btnNewProduct;
private Long bakeryId;
private Bundle params;
private TextView txtAnswer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //getLayoutInflater().inflate(R.layout.activity_product_admin, frameLayout);
    setContentView(R.layout.activity_product_admin);
    setTitle("Meus Produtos");

    Intent it = getIntent();
    params = it.getExtras();
    if (params != null) {
        bakeryId = params.getLong("bakeryId");
    }

    txtAnswer = (TextView) findViewById(R.id.textAnswer);
    rvProductAdmin = (RecyclerView) findViewById(R.id.product_list_admin);
    btnNewProduct = (Button) findViewById(R.id.btn_new_product);
    btnNewProduct.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            params.putLong("bakeryId", bakeryId);
            Intent intentFormProduct = new Intent(ProductAdminActivity.this, FormProductActivity.class);
            intentFormProduct.putExtras(params);
            startActivity(intentFormProduct);
        }
    });
    new ProductListAsyncTask(this).execute();
}

private class ProductListAsyncTask extends AsyncTask<Void, Void, CollectionResponseProduct> {
    ProductAdminActivity context;
    private ProgressDialog pd;

    public ProductListAsyncTask(ProductAdminActivity context) {
        this.context = context;
    }

    protected void onPreExecute(){
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setMessage("Listando Produtos...");
        pd.show();
    }

    protected CollectionResponseProduct doInBackground(Void... unused) {
        CollectionResponseProduct collectionResponseProduct = null;
        try {
            ProductApi.Builder builder = new ProductApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null).setRootUrl(URL);
            builder.setApplicationName(APP_NAME);
            ProductApi service =  builder.build();
            collectionResponseProduct = service.list().execute();
        } catch (Exception e) {
            Log.d("Erro", e.getMessage(), e);
        }
        return collectionResponseProduct;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    protected void onPostExecute(CollectionResponseProduct collectionResponseProduct) {
        pd.dismiss();
        if(collectionResponseProduct.size() > 0){
            List<Product> list = new ArrayList<>();
            List<Product> _list = collectionResponseProduct.getItems();
            for (Product productAux : _list) {
                Product product = new Product();
                product.setProductName(productAux.getProductName());
                product.setProductPrice(productAux.getProductPrice());
                product.setType(productAux.getType());
                product.setBakeryId(productAux.getBakeryId());
                product.setProductImage(productAux.getProductImage());
                if(Objects.equals(bakeryId, product.getBakeryId())){
                    list.add(product);
                }
            }
            rvProductAdmin.setLayoutManager(new LinearLayoutManager(ProductAdminActivity.this));
            rvProductAdmin.setAdapter(new ProductAdapter(list));
        } else {
            txtAnswer.setText("Não existem produtos cadastrados!");
        }
    }
}

}

Adapter:

public class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder> {

private final List<Product> products;

public ProductAdapter(List<Product> products) {
    this.products = products;
}

@Override
public ProductViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    final LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
    final View v = layoutInflater.inflate(R.layout.card_product, viewGroup, false);
    //final View v = layoutInflater.inflate(R.layout.item_product, viewGroup, false);
    return new ProductViewHolder(v);
}

@Override
public void onBindViewHolder(ProductViewHolder productViewHolder, int i) {
    productViewHolder.tvProductName.setText(products.get(i).getProductName());
    productViewHolder.tvPrice.setText(products.get(i).getProductPrice().toString());
    productViewHolder.tvCategory.setText(products.get(i).getType());
    //productViewHolder.tvItensSale.setText(products.get(i).getItensSale());

    String strBase64 = products.get(i).getProductImage();
    byte[] imgBytes = Base64.decode(strBase64, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);

    productViewHolder.ivProduct.setImageBitmap(bitmap);
}

@Override
public int getItemCount() {
    return products.size();
}
}

Exception:

FATAL EXCEPTION: main
                                                                  Process: com.gregmachado.panapp, PID: 8730
                                                                  java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
                                                                      at com.gregmachado.panapp.activity.ProductAdminActivity$ProductListAsyncTask.onPostExecute(ProductAdminActivity.java:106)
                                                                      at com.gregmachado.panapp.activity.ProductAdminActivity$ProductListAsyncTask.onPostExecute(ProductAdminActivity.java:70)
                                                                      at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                      at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
  • If you put your code here, I’ll help you!

  • I put the code, that Toast over there isn’t working, I don’t know if it has to do with Colletionresponse, first time I work with this kind of list.

2 answers

2


Here’s what you’re gonna do activity_product_admin.xml create a Textview

<TextView
        android:id="@+id/textResposta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Resposta"
        android:textStyle="bold"
        android:textColor="#ff00ff"
       />

In your class ProductAdminActivity you will instantiate your TextView, first declaring a variable of type TextView and then make the connection with the .xml.

private TextView textReposta;

Within your onCreate you do this way:

textResposta= (TextView) findViewById(R.id.textResposta);

There remains only replaces your Toast by the following code:

textResposta.setText("Não existem produtos cadastrados!");

That’s it! Hugs! Good Luck!

  • ai this. I also thought it was just that, but fires an Exception. I edited there and put.

  • @Grégorimachado help your brother. When you comment, you update your code or put it there otherwise it is difficult to know what you are missing.

  • I responded and went to update the code.

  • @Grégorimachado is not updated.

  • I put Exception at the end of the code. java.lang.Nullpointerexception: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null Object Reference

  • Anyway. I thought here and made several attempts. I managed to solve. I will post the solution.

  • @Grégorimachado brother, is to update your code with the changes I entered.

  • I just got an update

Show 3 more comments

0

Solution:

protected CollectionResponseProduct doInBackground(Void... unused) {
        CollectionResponseProduct collectionResponseProduct = null;
        ProductApi.Builder builder = new ProductApi.Builder(AndroidHttp.newCompatibleTransport(),
                new AndroidJsonFactory(), null).setRootUrl(URL);
        builder.setApplicationName(APP_NAME);
        ProductApi service =  builder.build();
        try {
            collectionResponseProduct = service.list().execute();
        } catch (Exception e) {
            Log.d("Erro", e.getMessage(), e);
        }
        return collectionResponseProduct;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    protected void onPostExecute(CollectionResponseProduct collectionResponseProduct) {
        pd.dismiss();
        List<Product> list = new ArrayList<>();
        List<Product> _list = collectionResponseProduct.getItems(); // fiz o get pro List antes
        if(_list == null){ // e fiz o teste aqui no List ao invés do Collection Response
            txtAnswer.setText("Não existem produtos cadastrados!");
        } else {
            for (Product productAux : _list) {
                Product product = new Product();
                product.setProductName(productAux.getProductName());
                product.setProductPrice(productAux.getProductPrice());
                product.setType(productAux.getType());
                product.setBakeryId(productAux.getBakeryId());
                product.setProductImage(productAux.getProductImage());
                if(Objects.equals(bakeryId, product.getBakeryId())){
                    list.add(product);
                }
            }
            rvProductAdmin.setLayoutManager(new LinearLayoutManager(ProductAdminActivity.this));
            rvProductAdmin.setAdapter(new ProductAdapter(list));
        }
    }
  • You know you don’t get any merit by answering your own question right?! It is much better to give the credits to those who help you, because you end up winning too with this. Hugs

  • face does not take me wrong. I do not care for the credits. Unlike you. From the first comment you responded with the air of superiority. Everything you told me to do, I’d already done. If I knew everything about programming I wouldn’t be asking for help. But I don’t think there’s anyone who knows everything about programming right. And if the problem is credit, I mark your answer as a solution.

  • By all means! Everyone has their thoughts and I respect yours! Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.