android数组列表为null

时间:2014-04-17 08:47:04

标签: android arraylist android-asynctask

我正在设计一个Android应用程序,该应用程序从网站下载信息并在屏幕上以数组列表的形式打印出包含该信息的列表。

但是,我使用的ArrayList没有正确加载,我的屏幕变成空白。

活动代码:

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



}

主要问题在于此部分:

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

&#34; if&#34;条件未满足:store.getProductes()为null。

这很奇怪,因为应用程序可以通过互联网DL信息,我可以在logcat输出中看到:由于某种原因它不会加载到ArrayList中。

你能帮我弄清楚我必须做些什么让ArrayList工作吗?

非常感谢你。

4 个答案:

答案 0 :(得分:1)

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

您在SuperAdapter cnstructer中传递null,您需要传递ArrrayList而不是传递null。

答案 1 :(得分:1)

以这种方式放置条件

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

答案 2 :(得分:1)

private ArrayList<Super> productes = new ArrayList<Super>():

你永远不会使用你的setProducts,所以这将是空的。

答案 3 :(得分:1)

首先删除以下代码

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

现在修改了下面的refreshListByJson()

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


}