2017-10-08 69 views
-3

看着就到這裏了幾篇文章我才知道,要聲明在Android Studio中的二維數組,你必須這樣做如何分配值,多維數組在Android Studio中

String[][] stations=new String[1][10]; 

而且將數據插入到二維陣列我創造了我這樣做

stations[1][0]= "New York"; 
stations[2][0]= "Boston"; 
stations[3][0]= "Las Vegas"; 
stations[4][0]= "Miami"; 
stations[5][0]= "Chicago"; 
stations[6][0]= "New England"; 
stations[7][0]= "Detroit"; 
stations[8][0]= "Michigan"; 
stations[9][0]= "Austin"; 

當我運行此我得到的錯誤信息

Unfortunately DB Has Stopped 

因此我決定註釋掉代碼,將字符串應用到數組中,並且應用程序完美運行。 我在做這些賦值操作有什麼問題?

繼承人我的源代碼:

public class MainActivity extends AppCompatActivity { 
Button trainSearch; 
String[][] stations=new String[1][10]; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    trainSearch=(Button)findViewById(R.id.button); 
    trainSearch.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      search(); 

     } 
    }); 

} 

public void search() 
{ 
    Toast.makeText(MainActivity.this, "function called Successfully", Toast.LENGTH_SHORT).show(); 
    /*stations[1][0]= "New York"; 
    stations[2][0]= "Boston"; 
    stations[3][0]= "Las Vegas"; 
    stations[4][0]= "Miami"; 
    stations[5][0]= "Chicago"; 
    stations[6][0]= "New England"; 
    stations[7][0]= "Detroit"; 
    stations[8][0]= "Michigan"; 
    stations[9][0]= "Austin";*/ 
    SQLiteDatabase db = openOrCreateDatabase("Train_list.db", SQLiteDatabase.CREATE_IF_NECESSARY , null); 
    try{ 
     String query = "CREATE TABLE IF NOT EXISTS Stations (" 
       + "Station_name VARCHAR);"; 
     db.execSQL(query); 
     Toast.makeText(MainActivity.this, "Table created", Toast.LENGTH_LONG).show(); 
     /*int i=0; 
     for(i=0;i<10;i++) 
     { 
      query = "INSERT or replace INTO stations (Station_name) VALUES(" + stations[0][i] + ");"; 
      db.execSQL(query); 
      Toast.makeText(MainActivity.this, "Added Staation"+stations[0][i], Toast.LENGTH_SHORT).show(); 
     }*/ 
    }catch (Exception e){ 
     Toast.makeText(MainActivity.this, "An Error has occured", Toast.LENGTH_SHORT).show(); 
    } 
} 
public void calladminactivity(View v) 
{ 
    startActivity(new Intent(MainActivity.this, adminlogin.class)); 

} 
} 
+2

你有索引切換。您正在將第一個初始化爲1,但嘗試訪問元素1-9。 –

回答

1

new String[1][10]意味着你有一個項目數組,此項目有10個項目的數組。

在您的代碼中,您嘗試訪問不存在的項目 - 站點[1],站點[2]等。只有站點[0]存在。

正確的代碼將是:

stations[0][1]= "New York"; 
stations[0][2]= "Boston"; 
... 
+0

順便說一句,'new String [1] [10]'完全沒有意義**:和聲明'new String [10]'相同(這也是**更容易管理**)。 –

+0

你是對的 - 我的假設是他將繼續研究代碼,因爲他說他需要多維數組。感謝您的評論。 – yakobom

+0

是的,你的答案是我的+1。我正在處理OP。 ;) –