我需要有关如何从tablayout中的edittext检索userinput值的帮助。我有4个选项卡,每个选项卡都有相同的editText小部件,这意味着我只实现了一个edittext视图。问题是,如果我在每个editText中放置一个值,我不知道如何检索它们,因为我不知道如何找到每个editText的位置,我甚至需要将它们放在我的数据库中,这是在sqlite中。有人会指导我吗感谢。
PS。如果需要,将添加代码。
编辑:
My_Notes_Add_Main.java
package com.zaid.recyclerviewsqlite.addNotes;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import com.zaid.recyclerviewsqlite.R;
import com.zaid.recyclerviewsqlite.mynote_databases.DatabaseHelper;
import com.zaid.recyclerviewsqlite.notes.DataModel;
public class My_Notes_Add_Main extends AppCompatActivity implements View.OnClickListener {
private final int numOfPages = 4; //viewpager has 4 pages
private final String[] pageTitle = {"Terms", "Definition", "Syntax", "Code"};
private ImageButton addNew;
My_Notes_Add_MyPagerAdapter adapter = new My_Notes_Add_MyPagerAdapter( null, numOfPages);
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_notes_add_main);
db = new DatabaseHelper(this);
addNew = (ImageButton)findViewById(R.id.addNew);
addNewTerms();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
for (int i = 0; i < numOfPages; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new My_Notes_Add_MyPagerAdapter(getSupportFragmentManager(), numOfPages);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
/** @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_notes_add_main_menu, menu);
return true;
} */
public void addNewTerms(){
addNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> listNotes= new ArrayList<String>();
for (int i = 0; i < adapter.getCount(); i++) {
My_Notes_Add_TabFragment fragment = adapter.getFragment(i);
if(fragment != null)
listNotes.add(fragment.getText());
}
DataModel model = new DataModel(listNotes.get(0),listNotes.get(1),
listNotes.get(2),listNotes.get(3));
db.InsertNewRecord(model);
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
My_Notes_Add_MyPagerAdapter.java
package com.zaid.recyclerviewsqlite.addNotes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
public class My_Notes_Add_MyPagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
private final SparseArray<Fragment> mPageReferences = new SparseArray<Fragment>();
public My_Notes_Add_MyPagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
@Override
public Fragment getItem(int position) {
My_Notes_Add_TabFragment fragment = (My_Notes_Add_TabFragment) My_Notes_Add_TabFragment.getInstance(position);
mPageReferences.put(position, fragment);
return fragment;
}
public int getCount() {
return numOfTabs;
}
public My_Notes_Add_TabFragment getFragment(int key) {
return (My_Notes_Add_TabFragment) mPageReferences.get(key);
}
}
My_Notes_Add_TabFragment.java
package com.zaid.recyclerviewsqlite.addNotes;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.zaid.recyclerviewsqlite.R;
public class My_Notes_Add_TabFragment extends Fragment {
private int position;
public TextView content;
//private ImageView image;
public static Fragment getInstance(int position) {
My_Notes_Add_TabFragment f = new My_Notes_Add_TabFragment();
Bundle args = new Bundle();
args.putInt("position", position);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get data from Argument
position = getArguments().getInt("position");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_notes_add_tab_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
content = (EditText) view.findViewById(R.id.textView);
}
public String getText(){
return content.getText().toString();
}
}
DatabaseHelper.java 注意数据库的注释插入是为了测试我的数据库是否正常工作
package com.zaid.recyclerviewsqlite.mynote_databases;
import java.util.ArrayList;
import java.util.List;
import com.zaid.recyclerviewsqlite.notes.DataModel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBASE = "my_notes";
public static final String TBLMYNOTES = "tblnotes";
public static final int DBVERSION = 1;
public static final String NOTE_TERM = "note_term";
public static final String NOTE_ID = "note_id";
public static final String NOTE_DEF = "note_def";
public static final String NOTE_SYNTAX = "note_syntax";
public static final String NOTE_CODE = "note_code";
public int currentID;
public DatabaseHelper(Context context) {
super(context, DBASE, null, DBVERSION);
// TODO Auto-generated constructor stub
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+TBLMYNOTES+" ("+ NOTE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NOTE_TERM+" TEXT, "+NOTE_DEF+" TEXT, "+NOTE_SYNTAX+" TEXT, "+NOTE_CODE+" TEXT )");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+TBLMYNOTES);
onCreate(db);
}
public void InsertNewRecord( DataModel datamodel ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues db_values = new ContentValues();
db_values.put(NOTE_TERM, datamodel.getTerm());
db_values.put(NOTE_DEF, datamodel.getDefinition());
db_values.put(NOTE_SYNTAX, datamodel.getSyntax());
db_values.put(NOTE_CODE, datamodel.getCode());
/** int countArr = values.size();
for( int i = 0; i < countArr; i++ ) {
db_values.put( fields.get(i), values.get(i) );
}
*/
db.insert(TBLMYNOTES, null, db_values);
db.close();
}
public Cursor getAllData(String tblname) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM "+tblname, null);
return result;
}
/**
* @return
*/
public List<DataModel> getAllDataModel(){
List<DataModel> dataList = new ArrayList<DataModel>();
String query = "SELECT * FROM " + TBLMYNOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(query, null);
while(c.moveToNext()){
/** DataModel model= new DataModel();
model.setId(Integer.parseInt(c.getString(0)));
model.setTerm(c.getString(1));
model.setDefinition(c.getString(2));
model.setSyntax(c.getString(3));
model.setCode(c.getString(4));
*/
int index0 = c.getColumnIndex(NOTE_ID);
int index1 = c.getColumnIndex(NOTE_TERM);
int index2 = c.getColumnIndex(NOTE_DEF);
int index3 = c.getColumnIndex(NOTE_SYNTAX);
int index4 = c.getColumnIndex(NOTE_CODE);
int id = c.getInt(index0);
String term = c.getString(index1);
String def = c.getString(index2);
String syn = c.getString(index3);
String code = c.getString(index4);
DataModel model = new DataModel(id, term, def, syn, code);
dataList.add(model);
}
return dataList;
}
public int DeleteRecord(String tblname, String strField, String strValue) {
SQLiteDatabase db = this.getWritableDatabase();
int status = db.delete(TBLMYNOTES , " "+strField+" = ? ", new String[] { strValue });
return status;
}
public int UpdateRecord(String tblname, ArrayList<String> Fields, ArrayList<String> Values) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues db_values = new ContentValues();
int countMaxArr = Fields.size();
String strFieldID = Fields.get(0);
String strFieldValue = Values.get(0);
for( int i = 0; i < countMaxArr; i++ ) {
db_values.put(Fields.get(i), Values.get(i));
}
int status = db.update(TBLMYNOTES, db_values, strFieldID+" = ? ", new String[] { strFieldValue });
return status;
}
public void setcurrID(int ID) {
currentID = ID;
}
public int getcurrID() {
return currentID;
}
public Cursor getRecordByID(String tblname, String Fieldname, String Fieldvalue) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM "+ TBLMYNOTES+" WHERE "+Fieldname+" = "+Fieldvalue, null);
return result;
}
}
DataModel.java
package com.zaid.recyclerviewsqlite.notes;
public class DataModel {
String term_;
String definition_;
int id_;
String syntax_;
String code_;
public DataModel(){
}
public DataModel(int id, String term, String def, String syntax, String code) {
this.term_ = term;
this.id_ = id;
this.definition_=def;
this.syntax_=syntax;
this.code_=code;
}
public DataModel(String term, String def, String syntax, String code) {
this.term_ = term;
this.definition_=def;
this.syntax_=syntax;
this.code_=code;
}
public String getTerm() {
return term_;
}
public String getDefinition(){
return definition_;
}
public String getSyntax() {
return syntax_;
}
public String getCode() {
return code_;
}
public int getId() {
return id_;
}
public void setTerm(String term){
this.term_= term;
}
public void setId(int id){
this.id_= id;
}
public void setDefinition(String definition){
this.definition_= definition;
}
public void setSyntax(String syntax){
this.syntax_= syntax;
}
public void setCode(String code){
this.code_= code;
}
}
logcat的
03-14 23:37:37.230: D/AndroidRuntime(4640): Shutting down VM
03-14 23:37:37.230: W/dalvikvm(4640): threadid=1: thread exiting with uncaught exception (group=0x55d52b20)
03-14 23:37:37.230: I/Process(4640): Sending signal. PID: 4640 SIG: 9
03-14 23:37:37.230: D/AndroidRuntime(4640): procName from cmdline: com.zaid.recyclerviewsqlite
03-14 23:37:37.230: E/AndroidRuntime(4640): in writeCrashedAppName, pkgName :com.zaid.recyclerviewsqlite
03-14 23:37:37.230: D/AndroidRuntime(4640): file written successfully with content: com.zaid.recyclerviewsqlite StringBuffer : ;com.zaid.recyclerviewsqlite
03-14 23:37:37.230: E/AndroidRuntime(4640): FATAL EXCEPTION: main
03-14 23:37:37.230: E/AndroidRuntime(4640): Process: com.zaid.recyclerviewsqlite, PID: 4640
03-14 23:37:37.230: E/AndroidRuntime(4640): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.zaid.recyclerviewsqlite/com.zaid.recyclerviewsqlite.addNotes.My_Notes_Add_Main}: java.lang.NullPointerException
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.os.Looper.loop(Looper.java:136)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.ActivityThread.main(ActivityThread.java:5021)
03-14 23:37:37.230: E/AndroidRuntime(4640): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 23:37:37.230: E/AndroidRuntime(4640): at java.lang.reflect.Method.invoke(Method.java:515)
03-14 23:37:37.230: E/AndroidRuntime(4640): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
03-14 23:37:37.230: E/AndroidRuntime(4640): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
03-14 23:37:37.230: E/AndroidRuntime(4640): at dalvik.system.NativeStart.main(Native Method)
03-14 23:37:37.230: E/AndroidRuntime(4640): Caused by: java.lang.NullPointerException
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:256)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
03-14 23:37:37.230: E/AndroidRuntime(4640): at com.zaid.recyclerviewsqlite.mynote_databases.DatabaseHelper.<init>(DatabaseHelper.java:30)
03-14 23:37:37.230: E/AndroidRuntime(4640): at com.zaid.recyclerviewsqlite.addNotes.My_Notes_Add_Main.<init>(My_Notes_Add_Main.java:24)
03-14 23:37:37.230: E/AndroidRuntime(4640): at java.lang.Class.newInstanceImpl(Native Method)
03-14 23:37:37.230: E/AndroidRuntime(4640): at java.lang.Class.newInstance(Class.java:1208)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
03-14 23:37:37.230: E/AndroidRuntime(4640): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
03-14 23:37:37.230: E/AndroidRuntime(4640): ... 11 more
答案 0 :(得分:1)
这是一个工作样本
public class My_Notes_Add_MyPagerAdapter extends FragmentPagerAdapter {
int numOfTabs;
private final SparseArray<Fragment> mPageReferences = new SparseArray<>();
public My_Notes_Add_MyPagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
@Override
public Fragment getItem(int position) {
My_Notes_Add_TabFragment fragment = My_Notes_Add_TabFragment.getInstance(position);
mPageReferences.put(position, fragment);
return }
@Override
public int getCount() {
return numOfTabs;
}
public My_Notes_Add_TabFragment getFragment(int key) {
return (My_Notes_Add_TabFragment) mPageReferences.get(key);
}
}
在您的片段My_Notes_Add_TabFragment.java中添加getText
方法
public String getText(){
return content.getText().toString();
}
如何使用它。在你的My_Notes_Add_Main.java
中@Override
public void onClick(View v) {
List<String> listNotes= new ArrayList<>();
for (int i = 0; i < adapter.getCount(); i++) {
My_Notes_Add_TabFragment fragment = adapter.getFragment(i);
if(fragment != null)
listNotes.add(fragment.getText());
else{
Toast.makeText(this,
"You need to fill " + pageTitle[i], Toast.LENGTH_LONG)
.show();
return;
}
}
DataModel model = new DataModel(yourId,listNotes.get(0),listNotes.get(1),
listNotes.get(2),listNotes.get(3))
//create your save to DB method with listText parameter
yourSaveToDB(listNotes);
}
希望它有所帮助!!