我收到java.lang.IllegalStateException:无法执行活动方法

时间:2014-08-12 06:13:29

标签: android sqlite

我正在开发一个应用程序,在其中我将一些数据存储在sqlite数据库中。然后单击按钮,从数据库中检索数据并尝试以表格格式存储它。 当我尝试将所有数据存储在textview中时,这工作正常,但不是以表格格式存储。现在,每当我尝试使用表格布局以表格格式存储数据时,我就会收到标题为“java.lang.illegalStateException:无法执行活动方法”的运行时异常。请帮我。提前谢谢。

下面是我的代码:

public class MainActivity extends Activity {
    TextView[] columsView;
     SQLiteDatabase db;
    //  TextView tv;
      EditText et1,et2;
      int k=0;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       //initialize all view objects
      // tv=(TextView)findViewById(R.id.textView1);
       et1=(EditText)findViewById(R.id.editText1);
       et2=(EditText)findViewById(R.id.editText2);
       columsView=new TextView[30];
       //create database if not already exist
       db= openOrCreateDatabase("Mydb", MODE_PRIVATE, null);
       //create new table if not already exist
       db.execSQL("create table if not exists mytable(name varchar, sur_name varchar)");
       }
       //This method will call on when we click on insert button
       public void insert(View v)
       {
        String name=et1.getText().toString();
        String sur_name=et2.getText().toString();
        et1.setText("");
        et2.setText("");
        //insert data into able
        db.execSQL("insert into mytable values('"+name+"','"+sur_name+"')");
       //display Toast
       Toast.makeText(this, "values inserted successfully.", Toast.LENGTH_LONG).show();
        }
       //This method will call when we click on display button
       public void display(View v)
       {
       //use cursor to keep all data
       //cursor can keep data of any data type
       Cursor c=db.rawQuery("select * from mytable", null);
       StringBuilder sb = new StringBuilder();

      // tv.setText("");
       //move cursor to first position
       c.moveToFirst();
       //fetch all data one by one
       do
       {
        //we can use c.getString(0) here
        //or we can get data using column index
        String name=c.getString(c.getColumnIndex("name"));
        String surname=c.getString(1);
        //display on text view
      //  sb.append(name).append(";").append(surname).append("_");
      /*  if(name==et1.getText().toString() && surname==et2.getText().toString())
        {
            Toast.makeText(getBaseContext(), "pass", Toast.LENGTH_LONG).show();
        }*/
        //tv.append("Name:"+name+" and SurName:"+surname+"\n");
        //move next position until end of the data
        TableLayout tableLayout = (TableLayout)findViewById(R.id.tab); 
        tableLayout.removeAllViews();
        TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        final String row=name+";"+surname;
        final String[] cols = row.split(";");
        for (int j = 0; j < 2; j++) {        
            final String col = cols[j];    

             columsView[k] = new TextView(this);  
            columsView[k].setText(String.format("%7s", col));                              
            tableRow.addView(columsView[k]);
            k++;
            tableLayout.addView(tableRow);
        }


       }while(c.moveToNext());

       }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
public void forgot(View v)
{
    Toast.makeText(getBaseContext(), "inside forgot", Toast.LENGTH_LONG).show();

    Intent i=new Intent(this,ForgotPass.class);
    startActivity(i);
    //moveTaskToBack(true);
            }

public void changepass(View v)
{
    Toast.makeText(getBaseContext(), "inside forgot", Toast.LENGTH_LONG).show();

    Intent i=new Intent(this,ChangePass.class);
    startActivity(i);
    //moveTaskToBack(true);
            }
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    super.onBackPressed();
    db.close();
}
}

这是我的xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
<EditText
   android:id="@+id/editText2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/editText1"
   android:layout_below="@+id/editText1"
   android:hint="Sur Name"
   android:maxLines="1"
   android:ems="10" />
<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/editText2"
   android:layout_alignRight="@+id/editText2"
   android:layout_below="@+id/editText2"
   android:text="Insert Values"
   android:onClick="insert"/>
 <Button
   android:id="@+id/button2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/button1"
   android:layout_alignRight="@+id/button1"
   android:layout_below="@+id/button1"
   android:onClick="display"
   android:text="Display all Values" />


<Button
   android:id="@+id/button3"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/button2"
   android:layout_alignRight="@+id/button2"
   android:layout_below="@+id/button2"
   android:onClick="forgot"
   android:text="forgot password" />

<Button
   android:id="@+id/button4"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/button3"
   android:layout_alignRight="@+id/button3"
   android:layout_below="@+id/button3"
   android:onClick="changepass"
   android:text="Change password" />

<ScrollView
   android:id="@+id/scrollView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentBottom="true"
   android:layout_alignParentLeft="true"
   android:layout_alignParentRight="true"
   android:layout_below="@+id/button4" >

 <!--  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
  <TextView android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:textSize="20sp"/>
  </LinearLayout> -->

       <TableLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1"
     android:id="@+id/tab"       
    >

    </TableLayout>

 </ScrollView>
     <TextView android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="20sp"/>
<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:ems="10"
    android:hint="Name"
    android:maxLines="1" />

</RelativeLayout>

以下是我得到的错误:

08-12 10:59:25.289: E/AndroidRuntime(4105): FATAL EXCEPTION: main
08-12 10:59:25.289: E/AndroidRuntime(4105): java.lang.IllegalStateException: Could not execute method of the activity
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.View$1.onClick(View.java:2144)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.View.performClick(View.java:2485)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.View$PerformClick.run(View.java:9080)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.os.Handler.handleCallback(Handler.java:587)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.os.Looper.loop(Looper.java:130)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at java.lang.reflect.Method.invokeNative(Native Method)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at java.lang.reflect.Method.invoke(Method.java:507)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at dalvik.system.NativeStart.main(Native Method)
08-12 10:59:25.289: E/AndroidRuntime(4105): Caused by: java.lang.reflect.InvocationTargetException
08-12 10:59:25.289: E/AndroidRuntime(4105):     at java.lang.reflect.Method.invokeNative(Native Method)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at java.lang.reflect.Method.invoke(Method.java:507)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.View$1.onClick(View.java:2139)
08-12 10:59:25.289: E/AndroidRuntime(4105):     ... 11 more
08-12 10:59:25.289: E/AndroidRuntime(4105): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.ViewGroup.addView(ViewGroup.java:1871)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.widget.TableLayout.addView(TableLayout.java:421)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.ViewGroup.addView(ViewGroup.java:1828)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.widget.TableLayout.addView(TableLayout.java:403)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.view.ViewGroup.addView(ViewGroup.java:1808)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at android.widget.TableLayout.addView(TableLayout.java:394)
08-12 10:59:25.289: E/AndroidRuntime(4105):     at com.example.datbase.MainActivity.display(MainActivity.java:89)
08-12 10:59:25.289: E/AndroidRuntime(4105):     ... 14 more

3 个答案:

答案 0 :(得分:0)

  

IllegalStateException:指定的子级已有父级。您必须首先在孩子的父母身上调用removeView()。

您在TableRow的{​​{1}}循环中一遍又一遍地添加相同的for

display()

将其添加到循环外部,或者如果您想要多行,请为每次迭代创建一个新的for (int j = 0; j < 2; j++) { // ... tableLayout.addView(tableRow); }

答案 1 :(得分:0)

错误

tableLayout.addView(tableRow);

指定的子(tableRow)已经是父级。

每次循环时都需要创建新的TableRow,如下所示:

    final String row=name+";"+surname;
    final String[] cols = row.split(";");
    for (int j = 0; j < cols.length; j++) {        
        final String col = cols[j]; 
        TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));   

        columsView[k] = new TextView(this);  
        columsView[k].setText(String.format("%7s", col));                              
        tableRow.addView(columsView[k]);
        k++;
        tableLayout.addView(tableRow);
    }

这样,您就可以将新表格行添加到表格布局中。希望它有所帮助。

编辑:

你得到了cols [2]的ArrayIndexOutOfBound,因为它只有2个元素,cols [0]和cols [1]。

更改

for (int j = 0; j < 2; j++)

for (int j = 0; j < cols.length; j++)

希望这有帮助。

答案 2 :(得分:0)

删除此

 TableRow tableRow = new TableRow(this);

并将其添加到

   for (int j = 0; j < 2; j++) {        
        final String col = cols[j];    

        columsView[k] = new TextView(this);  
        columsView[k].setText(String.format("%7s", col));   
        TableRow tableRow = new TableRow(this);  
        tableRow.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));                         
        tableRow.addView(columsView[k]);
        k++;
        tableLayout.addView(tableRow);
    }