【问题标题】:android array list nullandroid数组列表空
【发布时间】:2014-04-17 08:47:04
【问题描述】:

我正在设计一个 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());    
       }
    }

“if”条件不满足:store.getProductes() 为空。

这很奇怪,因为该应用可以 DL 来自互联网的信息,我可以在 logcat 输出中看到:由于某种原因它没有加载到 ArrayList 中。

您能帮我弄清楚我必须做什么才能使 ArrayList 工作吗?

非常感谢。

【问题讨论】:

  • 致所有回答的人:我还没有制作任何 cmets,因为我一直在努力让我的模拟器工作,在它工作之前,我无法测试这些建议的更改将如何影响我的应用程序。一旦我能够测试它们,我会回复。

标签: android arraylist android-asynctask


【解决方案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,您需要传递 ArrayList 而不是传递 null。

【讨论】:

  • 当我尝试编写“ArrayList productes”时,它不会将其识别为变量。我明白你的意思,但我不知道如何实现它。
  • 您能否查看我发布的新答案(大约 44 分钟前)
【解决方案2】:

这样设置条件

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

【讨论】:

  • 是的,但这不会改变任何事情。它可以防止应用程序因 NullPointerException 而崩溃,但不会加载 ArrayList。
【解决方案3】:
private ArrayList<Super> productes = new ArrayList<Super>():

您也从不使用您的 setProducts,所以这将是空的。

【讨论】:

  • 尽管如此,ArrayList 仍然是空白的。有任何想法吗?来自互联网的信息被成功DLed。
  • 问题可能出在您的解析器上。但我从不使用 Gson lib。我使用过 org.json android default。
【解决方案4】:

首先删除下面的代码

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


}

【讨论】:

  • 我已经按照你说的尝试过了,但是屏幕仍然是空白的。
猜你喜欢
  • 2015-01-31
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 2015-06-13
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多