2015-07-19 32 views
-5

我有這樣一個類:如何在一個方法內修改數組?

import android.content.Context; 
import android.graphics.Color; 
import android.util.TypedValue; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 

public class workingOneWayAdapter extends BaseAdapter { 

    private Context mContext; 

    public workingOneWayAdapter(Context c) { 
     mContext = c; 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     TextView workingLabel; 
     if (convertView == null) { 
      workingLabel = new TextView(mContext); 
      workingLabel.setLayoutParams(new MyGridView.LayoutParams(85, 85)); 
      workingLabel.setPadding(10, 5, 5, 5); 
      workingLabel.setTextColor(Color.parseColor("#000000")); 
      workingLabel.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19); 
      workingLabel.setSingleLine(); 

      setTimes(); 

     } else { 
      workingLabel = (TextView) convertView; 
     } 

     workingLabel.setText(workingOneWayArray[position]); 
     return workingLabel; 
    } 

    String[] workingOneWayArray; 

    void setTimes() { 

     workingOneWayArray = new String[] { "00:00" };  
    } 

    public int getCount() { 
     return workingOneWayArray.length; 
    } 
} 

但它使我的應用程序崩潰。我需要在該方法內編輯數組,因爲該數組可以從該類的其他部分訪問。你能告訴我什麼是錯的嗎?謝謝!

+0

你能否提供這個類的更多代碼,因爲沒有什麼不對,也嘗試調試你的android應用程序 –

+0

該應用程序在getCount()方法崩潰,但我不知道爲什麼 – BigK

+0

也許你沒有打電話給你setTimes方法在發出你的getCount之前。向我們展示您的完整代碼 – Constantin

回答

0

此代碼工作正常,但如果我按相反順序調用兩個方法,它將崩潰。

也可以考慮把你的setTimes調用在構造函數中

public test() { 
    setTimes(); 
} 

或簡單地創建你的數組內聯......

String[] workingOneWayArray = new String[] { "00:00" }; 

這裏是工作的代碼

public class test { 


    String[] workingOneWayArray; 

    void setTimes() { 

    // THIS DOESN'T WORK 

     workingOneWayArray = new String[] { "00:00" }; 

    } 

    public int getCount() { 
     return workingOneWayArray.length; 
    } 

    public static void main(String[] args) { 
    test t = new test(); 

    t.setTimes(); 
    t.getCount(); 

    } 

} 
+0

如果我這樣做,我會得到:「workingOneWayAdapter中的(Context)不能應用」 – BigK

+0

如果你不能運行這個自包含的代碼,那麼你的問題不僅僅是你的數組 – Constantin

0

如果陣列從未被初始化,然後getCount()方法將拋出異常,因爲se workingOneWayArray不是數組,因此沒有.length屬性。確保getCount()從未在setTimes()之前被調用。

0

解決了這個變化:

String[] workingOneWayArray; 

本:

String[] workingOneWayArray = new String[1]; 

謝謝大家。