2013-07-12 4 views
2

Я создал приложение для Android, которое берет некоторые данные, используя поле editText, например, имя, контакт, одну кнопку радиогруппы, две кнопки для сохранения и просмотра сохраненных данных и счетчика и сохраняет эту информацию в базе данных при нажатии кнопки сохранения. Данные отображаются в нижней части экрана при нажатии кнопки просмотра. Обычно счетчик показывает значение 18 по умолчанию. Все в порядке, когда я открываю приложение и нажимаю кнопку сохранения после ввода полей, которые он сохраняет, и когда кнопка просмотра отображаются сжатые данные, но я не могу вставить больше данных, открыв приложение один раз, потому что содержимое счетчика теперь скрыто. Для этого мне нужно закрыть приложение, а затем открыть его еще раз. Как преодолеть эту проблему. Любой плз запустить коды и посмотреть, что проблемаКак преодолеть ситуацию, когда содержимое прядильника скрыто?

.xml файл:

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<LinearLayout 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/textContcat" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:paddingLeft="5dp" 
     android:text="@string/name" 
     android:textSize="20sp" /> 

    <EditText 
     android:id="@+id/editName" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:ems="10" 
     android:hint="@string/namehint" 
     android:inputType="textPersonName" 
     android:paddingRight="5dp" 
     android:textSize="20sp" > 

     <requestFocus /> 
    </EditText> 
</LinearLayout> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/textAge" 
     android:layout_width="wrap_content" 
     android:layout_height="37dp" 
     android:gravity="center" 
     android:paddingLeft="5dp" 
     android:paddingRight="20dp" 
     android:text="@string/age" 
     android:textSize="20sp" /> 

    <Spinner 
     android:id="@+id/spAge" 
     android:layout_width="80dp" 
     android:layout_height="match_parent" 
     android:layout_weight="0.00" 
     android:clickable="true" 
     android:gravity="top|center" 
     android:paddingRight="20dp" 
     android:textSize="20sp" /> 
</LinearLayout> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/textContcat" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:paddingLeft="5dp" 
     android:text="@string/contact" 
     android:textSize="20sp" /> 

    <EditText 
     android:id="@+id/editContact" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:ems="10" 
     android:hint="@string/contacthint" 
     android:inputType="number" 
     android:paddingRight="5dp" 
     android:textSize="20sp" /> 
</LinearLayout> 

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="0dp" 
    android:orientation="horizontal" > 

    <TextView 
     android:id="@+id/sLabel" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:gravity="left|center" 
     android:paddingLeft="5dp" 
     android:paddingRight="10dp" 
     android:text="@string/sx" 
     android:textSize="20sp" /> 

    <RadioGroup 
     android:id="@+id/RadioGroup01" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <RadioButton 
      android:id="@+id/malebutton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:checked="true" 
      android:text="@string/mal" 
      android:textSize="20sp" /> 

     <RadioButton 
      android:id="@+id/femalebutton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/femal" 
      android:textSize="20sp" /> 
    </RadioGroup> 
</LinearLayout> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 

    <Button 
     android:id="@+id/savebutton" 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="80dp" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:text="@string/save" 
     android:textSize="20sp" /> 

    <Button 
     android:id="@+id/viewbutton" 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="80dp" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:gravity="center" 
     android:text="@string/view" 
     android:textSize="20sp" /> 
</LinearLayout> 

<View 
    android:layout_width="fill_parent" 
    android:layout_height="1dp" 
    android:background="@android:color/darker_gray" /> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" > 

    <TableLayout 
     android:id="@+id/tableLayout1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" > 

     <TableRow> 
     </TableRow> 
    </TableLayout> 

    <View 
     android:layout_width="fill_parent" 
     android:layout_height="1dp" 
     android:background="@android:color/darker_gray" /> 

    <TextView 
     android:id="@+id/tvSQLinfo" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:padding="5dp" 
     android:text="@string/nullvalue" 
     android:textColor="@color/text_color" 
     android:textSize="20sp" > 
    </TextView> 
</LinearLayout> 

.java файл:

public class SqlLiteExample extends Activity implements OnClickListener, 
OnItemSelectedListener { 
Button sqlUpdate, sqlView; 
EditText etName, etContact; 
RadioGroup myRadioGrp; 
RadioButton rbtn1, rbtn2; 
Spinner sp; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.sqlliteexample); 
sqlUpdate = (Button) findViewById(R.id.savebutton); 
etName = (EditText) findViewById(R.id.editName); 
etContact = (EditText) findViewById(R.id.editContact); 
rbtn1 = (RadioButton) findViewById(R.id.malebutton); 
rbtn2 = (RadioButton) findViewById(R.id.femalebutton); 
sqlView = (Button) findViewById(R.id.viewbutton); 
sqlView.setOnClickListener(this); 
sqlUpdate.setOnClickListener(this); 

uI(); 
spElements(); 

} 

private void spElements() { 
// TODO Auto-generated method stub 
List<String> ages = new ArrayList<String>(); 
for (int i = 18; i <= 99; i++) { 
    ages.add(String.valueOf(i)); 
} 
// Creating adapter for spinner 
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, 
     android.R.layout.simple_spinner_item, ages); 
// Drop down layout style - list view with radio button 
dataAdapter 
     .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
// attaching data adapter to spinner 
sp.setAdapter(dataAdapter); 
} 

private void uI() { 
// TODO Auto-generated method stub 
sp = (Spinner) findViewById(R.id.spAge); 
sp.setOnItemSelectedListener(this); 
} 

@Override 
public void onClick(View arg0) { 
// TODO Auto-generated method stub 
switch (arg0.getId()) { 
case R.id.savebutton: 
    boolean didWork = true; 
    try { 
     String name = etName.getText().toString(); 
     String age = (String) sp.getSelectedItem(); 
     String contact = etContact.getText().toString(); 

     myRadioGrp = (RadioGroup) findViewById(R.id.RadioGroup01); 
     String sex = ((RadioButton) this.findViewById(myRadioGrp 
       .getCheckedRadioButtonId())).getText().toString(); 

     MyDB entry = new MyDB(SqlLiteExample.this); 
     entry.open(); 
     entry.createEntry(name, age, contact, sex); 
     entry.close(); 
    } catch (Exception e) { 
     didWork = false; 
     String error = e.toString(); 
     Dialog d = new Dialog(this); 
     d.setTitle("Error"); 
     TextView tv = new TextView(this); 
     tv.setText(error); 
     d.setContentView(tv); 
     d.show(); 
    } finally { 
     if (didWork) { 
      Dialog d = new Dialog(this); 
      d.setTitle("Updated"); 
      TextView tv = new TextView(this); 
      tv.setText("Succesfully"); 
      d.setContentView(tv); 
      d.show(); 
     } 
    } 
    break; 
case R.id.viewbutton: 
    Intent i = new Intent("com.bysakiralam.mydatabase.DISPLAYRECORDS"); 
    startActivity(i); 
    break; 
} 
} 

@Override 
public void onItemSelected(AdapterView<?> main, View arg1, int position, 
    long Id) { 
// TODO Auto-generated method stub 

} 

@Override 
public void onNothingSelected(AdapterView<?> arg0) { 
// TODO Auto-generated method stub 

} 
} 

Displayrecords.java : 

public class DisplayRecords extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.sqlliteexample); 
    TextView tv = (TextView) findViewById(R.id.tvSQLinfo); 
    MyDB info = new MyDB(this); 

    try { 
     info.open(); 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    String data = info.getData(); 
    info.close(); 
    tv.setText(data); 
} 

} 

MyDB.java:

public class MyDB { 
public static final String KEY_ROWID = "_id"; 
public static final String KEY_NAME = "persons_name"; 
public static final String KEY_AGE = "persons_age"; 
public static final String KEY_CONTACT = "persons_contact"; 
public static final String KEY_SEX = "gender"; 

private static final String DATABASE_NAME = "MyDatabase"; 
private static final String DATABASE_TABLE = "peopleTable"; 
private static final int DATABASE_VERSION = 1; 

private DbHelper ourHelper; 
private final Context ourContext; 
private SQLiteDatabase ourDatabase; 

private static class DbHelper extends SQLiteOpenHelper { 

    public DbHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     // TODO Auto-generated method stub 
     db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID 
       + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME 
       + " TEXT NOT NULL, " + KEY_AGE + " TEXT NOT NULL, " 
       + KEY_CONTACT + " TEXT NOT NULL, " + KEY_SEX 
       + " TEXT NOT NULL)"); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     // TODO Auto-generated method stub 
     db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 
     onCreate(db); 
    } 
} 

public MyDB(Context c) { 
    ourContext = c; 
} 

public MyDB open() throws SQLException { 
    ourHelper = new DbHelper(ourContext); 
    ourDatabase = ourHelper.getWritableDatabase(); 
    return this; 
} 

public void close() { 
    ourHelper.close(); 
} 

public long createEntry(String name, String age, String contact, String sex) { 
    // TODO Auto-generated method stub 
    ContentValues cv = new ContentValues(); 
    cv.put(KEY_NAME, name); 
    cv.put(KEY_AGE, age); 
    cv.put(KEY_CONTACT, contact); 
    cv.put(KEY_SEX, sex); 
    return ourDatabase.insert(DATABASE_TABLE, null, cv); 
} 

public String getData() { 
    // TODO Auto-generated method stub 
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AGE, 
      KEY_CONTACT, KEY_SEX }; 
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, 
      null, null); 
    String result = ""; 

    int iRow = c.getColumnIndex(KEY_ROWID); 
    int iName = c.getColumnIndex(KEY_NAME); 
    int iAGE = c.getColumnIndex(KEY_AGE); 
    int iCONTACT = c.getColumnIndex(KEY_CONTACT); 
    int iSEX = c.getColumnIndex(KEY_SEX); 

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { 
     result = result + c.getString(iRow) + "\t\t" + c.getString(iName) 
       + "\t" + c.getString(iAGE) + "\t\t" + c.getString(iCONTACT) 
       + "\t" + c.getString(iSEX) + "\n"; 
    } 
    return result; 
} 
} 

ответ

0

Возможно, вам нужно сбросить spinner после сохранения или просмотра записи? (Возможно, в методах onClick кнопок save/view) Также файл xml не выглядит правильным, так как у вас есть линейная компоновка в ScrollView.

+0

Какой должен быть файл xml ... можете ли вы помочь PLZ.? –

+0

как сбросить счетчик в методе onClick. Я использовал spinner.setSelection (position), но не работал. –

+0

Линейная компоновка должна быть первой, затем ScrollView, а затем остальной. Также закройте nette