0

I'm designing an Android app that downloads information from a website and prints a list on-screen with that information in the form of an Array List.

However, the ArrayList I use doesn't load correctly and my screen becomes blank.

Activity code:

Tenda.java

public class Tenda extends Activity implements OnItemClickListener, LocationListener {

    ProgressDialog lDialog;
    String json_string;
    SuperAdapter adapter_super;
    int user_id;
    private LocationManager locationManager;
    public String provider;
    private String  lattitude , longitude; 

    /*************************************************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tenda);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        init_conf();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tenda, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_update:
                updateList();
                return true;
            case R.id.menu_search:
                alert_search();
                return true;   
            case R.id.menu_cancel:
                finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {

        TextView stock = (TextView) view.findViewById(R.id.list_product_stock);
        int num_stock = Integer.parseInt(stock.getText().toString()) ; 

        if(num_stock!=0){
            ArrayList<Super> productes=adapter_super.getItems_producte();
            Super current_product= productes.get(position);

            alert_buy(num_stock,current_product);
        }
        else
        {
            Toast.makeText(this, "OUT OF STOCK", Toast.LENGTH_LONG).show();
        }

    }

    private void init_conf(){

        Bundle extras = getIntent().getExtras();
        user_id = extras.getInt("user_id");

        Toast.makeText(this, "user id"+Integer.toString(user_id), Toast.LENGTH_LONG).show();

        ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
        adapter_super = new SuperAdapter(Tenda.this,null);
        lsv_producto.setAdapter(adapter_super);
        lsv_producto.setOnItemClickListener(this);
        updateList();

    }

    private void updateList(){
        loading();
        String url = "http://www.v2msoft.com/clientes/lasalle/curs-android/products.php?user_id="+user_id;

        boolean is_con=is_connected();

        if(is_con){
            Log.i("Connection", "true");
            AsyncTask(url);
            Toast.makeText(this, "connected internet", Toast.LENGTH_LONG).show();
        }
        else{
            json_string=storeRead();
            refreshListByJson(json_string);
            Toast.makeText(this, "not connected internet", Toast.LENGTH_LONG).show();
        }

    }

    private void search(String text){
        loading();
        String url="http://www.v2msoft.com/clientes/lasalle/curs-android/search.php?user_id="+user_id+"&q="+text;

        boolean is_con=is_connected();
        if(is_con){
            Log.i("search URL", url);
            Toast.makeText(this, url, Toast.LENGTH_LONG).show();
            searchAsyncTask(url);
        }
        else{
            Toast.makeText(this, "NO CONNECTION", Toast.LENGTH_LONG).show();
        }


    }

private void buy(Super producte, int value){

        int product_id=  producte.getId();

        String url="http://www.v2msoft.com/clientes/lasalle/curs-android/buy.php?user_id="+user_id+
                    "&product_id="+product_id+
                    "&items="+value+
                    "&lat="+1+
                    "&long="+1;

        Toast.makeText(this, url, Toast.LENGTH_LONG).show();

    }

    private void AsyncTask(String url){
        LongAsyncTask task = new LongAsyncTask();
        task.execute(url);
    }

    private void searchAsyncTask(String url){
        SearchAsyncTask task = new SearchAsyncTask();
        task.execute(url);
    }

    public void alert_search(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title");

        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String m_Text = input.getText().toString();
                Toast.makeText(getApplicationContext(), m_Text, Toast.LENGTH_LONG).show();
                search(m_Text);
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();

    }

    public void alert_buy(int max_value,final Super producte){

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("BUY");

        final NumberPicker number= new NumberPicker(this);
        number.setMaxValue(max_value);
        number.setMinValue(0);
        builder.setView(number);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int value= number.getValue();
                Toast.makeText(getApplicationContext(), value+"", Toast.LENGTH_LONG).show();
                buy(producte,value);
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();

    }

    /*************************ASYNC TASK************************/

    public class LongAsyncTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... url) {
            String url_result= conect(url[0]);
            Log.i("DO IN BACKGROUND", url_result);
            return url_result;

        }
       protected void onPostExecute(String url_result) {
           Log.i("On Post EXECUTE", url_result);
           json_string= url_result;
           storeWrite(json_string);
           refreshListByJson(json_string);//line 257
       }

    }

        public class SearchAsyncTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... url) {
            String url_result= conect(url[0]);
            Log.i("Search result", url_result);
            return url_result;

        }

       protected void onPostExecute(String url_result) {
           Log.i("On Post EXECUTE SEARCH", url_result);
           json_string= url_result;
           Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
           refreshListByJson(json_string);
       }

    }

    public class BuyAsyncTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... url) {
            String url_result= conect(url[0]);
            Log.i("buy result", url_result);
            return url_result;

        }
       protected void onPostExecute(String url_result) {
           Log.i("On Post EXECUTE SEARCH", url_result);
           json_string= url_result;
           Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
       }

    }

    /*************************************************/

    private void refreshListByJson(String json){//line 300
        lDialog.dismiss();
       Store store=Store.newStore(json);
       if (store.getProductes() != null)
       {
           Log.i("store-nom", "" + store.getStore());//line 305
           Log.i("store-producte", "" + store.getProductes().toString()); //line 306
           adapter_super.setItems_producte(store.getProductes());    
       }
    }

    private void storeWrite(String data){
        String FILENAME = "json_store";

        FileOutputStream fos;
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i("Write STORAGE", data);

    }

    private String storeRead(){
        String FILENAME = "json_store";

        FileInputStream  fis;
        StringBuilder fileContent = new StringBuilder();
        try {
            fis= openFileInput (FILENAME);
            BufferedReader br= new BufferedReader(new InputStreamReader(fis));
            String line;

            while((line = br.readLine())!= null)
            {
                fileContent.append(line);
            }
            br.close();
            fis.close();
            Log.i("READ STORAGE", fileContent.toString());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return fileContent.toString();
    }

    public String conect(String url_string){

        HttpURLConnection con = null;
        BufferedReader reader= null;

        try{
            URL url = new URL(url_string);
            con = (HttpURLConnection)url.openConnection();

            reader= new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line ="";
            StringBuffer responseBuffer = new StringBuffer();

            while((line=reader.readLine())!=null)
            {
                responseBuffer.append(line);
            }

            return responseBuffer.toString(); 
        }
        catch(Exception ex){
            Log.e(getClass().getName(), ex.getMessage(),ex);
            return  null;
        }

    }

    public boolean is_connected(){
        ConnectivityManager conMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conMgr.getActiveNetworkInfo();
          if (i == null)
            return false;
          if (!i.isConnected())
            return false;
          if (!i.isAvailable())
            return false;
          return true;
    }

    private void loading(){
         lDialog = new ProgressDialog(this);
         lDialog.setMessage("Loading...");
         lDialog.setCancelable(false);
         lDialog.show();
    }


/*** Location ***/

@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
int lat = (int) (arg0.getLatitude());
int lng = (int) (arg0.getLongitude());
lattitude = "Lattitude: "+ lat ;
longitude = "Longitude: "+ lng; 
}

@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
////TODO Auto-generated method stub

}               

}

Store.java

    public class Store {

    private String store;
    private ArrayList<Super> productes;

    public String getStore() {
        return store;
    }
    public void setSuper(String store) {
        this.store = store;
    }
    public ArrayList<Super> getProductes() {
        return productes;
    }
    public void setProductes(ArrayList<Super> productes) {
        this.productes = productes;
    }

    static Store newStore(String json_string){

        Gson gson= new Gson();

        Store store = gson.fromJson(json_string,Store.class);

        return store;

    }


}


    }

Super.java

public class Super {

    private int id;
    private String fabricant;
    private String nom;
    private float preu;
    private int stock;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFabricant() {
        return fabricant;
    }
    public void setFabricant(String fabricant) {
        this.fabricant = fabricant;
    }
    public String getNom() {
        return nom;
    }
    public void setNom(String nom) {
        this.nom = nom;
    }
    public float getPreu() {
        return preu;
    }
    public void setPreu(float preu) {
        this.preu = preu;
    }
    public int getStock() {
        return stock;
    }
    public void setStock(int stock) {
        this.stock = stock;
    }

}

LongAsyncTask.java

public class LongAsyncTask extends AsyncTask<String,String,String>{

    @Override
    protected String doInBackground(String... arg0) {

        return null;
    }


   protected void onPostExecute(String result) {

   }

}

SuperAdapter.java

public class SuperAdapter extends BaseAdapter {


    public ArrayList<Super> getItems_producte() {
        return items_producte;
    }

    private Activity activity;
    private ArrayList<Super> items_producte;

    public SuperAdapter(Activity activity, ArrayList<Super> items_producte){
        this.activity = activity;
        this.items_producte= items_producte;
    }

        @Override
    public int getCount() {
        if(items_producte==null){
            return 0;
        }
        else{
            return items_producte.size();
        }   }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return items_producte.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View contentView, ViewGroup Parent) {
        // TODO Auto-generated method stub
        View view = contentView;

        if(view==null){
            LayoutInflater inflate =(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflate.inflate(R.layout.info_product, null,false);
        }

        Super item_producte = items_producte.get(position);

        TextView id = (TextView)view.findViewById(R.id.list_product_id);
        TextView fabricant = (TextView)view.findViewById(R.id.list_product_fabricant);
        TextView nom = (TextView)view.findViewById(R.id.list_product_nom);
        TextView preu = (TextView)view.findViewById(R.id.list_product_preu);
        TextView stock = (TextView)view.findViewById(R.id.list_product_stock);

        id.setText(Integer.toString(item_producte.getId()));
        fabricant.setText(item_producte.getFabricant());
        nom.setText(item_producte.getNom());
        preu.setText(Float.toString(item_producte.getPreu()));
        stock.setText(Integer.toString(item_producte.getStock()));

        fabricant.setTextColor(activity.getResources().getColor(R.color.fabricant));
        nom.setTextColor(activity.getResources().getColor(R.color.fabricant));
        preu.setTextColor(activity.getResources().getColor(R.color.fabricant));
        stock.setTextColor(activity.getResources().getColor(R.color.fabricant));

        if(position%2==0){
            view.setBackgroundColor(activity.getResources().getColor(R.color.files_parelles));

        }
        else{
            view.setBackgroundColor(activity.getResources().getColor(R.color.files_imparelles));
        }

        /*STOCK COLOR*/
        if(item_producte.getStock()<=0){
            view.setBackgroundColor(activity.getResources().getColor(R.color.stock_null_bg));

            fabricant.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
            nom.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
            preu.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));
            stock.setTextColor(activity.getResources().getColor(R.color.stock_null_tx));

        }


        return view;
    }


    public void setItems_producte(ArrayList<Super> items_producte) {
        this.items_producte = items_producte;
        this.notifyDataSetChanged();
    }



}

The main problem is located in this section:

private void refreshListByJson(String json){//line 300
        lDialog.dismiss();
       Store store=Store.newStore(json);
       if (store.getProductes() != null)
       {
         Log.i("store-nom", "" + store.getStore());//line 305
        Log.i("store-producte", "" + store.getProductes().toString()); //line 306
           adapter_super.setItems_producte(store.getProductes());    
       }
    }

The "if" condition is not fulfilled: store.getProductes() is null.

It's strange because the app can DL the info from internet and I can see that in the logcat output: for some reason it doesn't load into the ArrayList.

Could you please help me in figuring out what I must do for the ArrayList to work?

Thank you very much.

1
  • To all who replied: I haven't made any comments yet because I've been struggling to make my emulator work and until it works I can't test how these suggested changes will affect my app. Once I have been able to test them I will reply. Commented Apr 17, 2014 at 10:31

4 Answers 4

1
    ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
    adapter_super = new SuperAdapter(Tenda.this,null);
    lsv_producto.setAdapter(adapter_super);

You are passing null in SuperAdapter cnstructer, you need to pass ArrrayList instead of passing null.

Sign up to request clarification or add additional context in comments.

2 Comments

When I try to write "ArrayList<Super> productes" it doesn't recognize it as a variable. I understand what you mean but I don't see how to implement it.
Can you please check my new answer posted (about 44 mins ago)
1

Put condition this way

if (store.getProductes() != null && store.getProductes().size()>0){
}

1 Comment

Yes, but that doesn't change anything. It prevents the app from crashing out of NullPointerException but the ArrayList doesn't load.
1
private ArrayList<Super> productes = new ArrayList<Super>():

You never use your setProducts too so this will be empty.

2 Comments

Despit this, the ArrayList continues to be on blank. Any ideas? The information from Internet is successfully DLed.
problem may be with your parser. But I never use Gson lib. I have worked with org.json android default.
1

First Remove the below code

ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
adapter_super = new SuperAdapter(Tenda.this,null);
lsv_producto.setAdapter(adapter_super);

Now modified the refreshListByJson() as below

private void refreshListByJson(String json){//line 300
    lDialog.dismiss();
   Store store=Store.newStore(json);
   if (store.getProductes() != null)
   {
     Log.i("store-nom", "" + store.getStore());//line 305
    Log.i("store-producte", "" + store.getProductes().toString()); //line 306
       adapter_super.setItems_producte(store.getProductes());    
   }

   //////////////////
   ListView lsv_producto = (ListView)findViewById(R.id.list_productes);
      adapter_super = new SuperAdapter(Tenda.this,store.getProductes());
      lsv_producto.setAdapter(adapter_super);
  ////////////////////


}

1 Comment

I've tried this as you said but the screen remains in blank nevertheless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.