I have a form which asks values like name, gender etc. These values are stored in a table with a primary key field Id which is not entered by the user. I have to enter it with incrementing its value every time a new record is saved by using SharedPreferences. How do I do that?
This is my class file:
saveBtn = (Button) view.findViewById(R.id.save);
saveBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
String name = nameEdt.getText().toString().trim();
String trainingTypes = trainingTypesSpn.toString().trim();
String trainerProfile = trainerProfileSpn.toString().trim();
String description = descriptionEdt.toString().trim();
String plannedBudget = plannedBudgetNp.toString().trim();
String startDt = startDtEdt.toString().trim();
String endDt = endDtEdt.toString().trim();
TrainingDetailsDTO dto = new TrainingDetailsDTO();
dto.setName(name);
dto.setTrainingTypes(trainingTypes);
dto.setTrainerProfile(trainerProfile);
dto.setDescription(description);
dto.setPlannedBudget(plannedBudget);
dto.setStartDt(startDt);
dto.setEndDt(endDt);
SQLiteDatabase database = DBHandler.getInstance(mActivity).getDBObject(1);
boolean isInsert = TrainingDetailsDAO.getInstance().insert(dto, database);
if (isInsert)
{
Toast.makeText(mActivity, "Inserted Successfully", Toast.LENGTH_SHORT).show();
mActivity.popFragments();
mActivity.pushFragments(Constants.TAB_HOUSE, new HouseConstructionTrack(), false, false);
}
else
{
Toast.makeText(mActivity, "Insert Problem", Toast.LENGTH_SHORT).show();
}
mActivity.popFragments();
}
});
This is my insert method in DAO class:
public boolean insert(DTO dtoObject, SQLiteDatabase dbObject)
{
TrainingDetailsDTO dto = (TrainingDetailsDTO) dtoObject;
ContentValues cValues = new ContentValues();
cValues.put("TrainingDetailsId", "TR001");
cValues.put("name" , dto.getName());
cValues.put("trainingTypes" , dto.getTrainingTypes());
cValues.put("trainerProfile", dto.getTrainerProfile());
cValues.put("description" , dto.getDescription());
cValues.put("plannedBudget" , dto.getPlannedBudget());
cValues.put("startDt" , dto.getStartDt());
cValues.put("endDt" , dto.getEndDt());
dbObject.insert("TRAINING_DETAILS", null, cValues);
return false;
}
Here I am only able to give Id for the first record. How to generate subsequent Ids using SharedPreferences?
Extend BaseColumns in Android. It automatically has _ID field which is incremented automatically.
public static abstract class User implements BaseColumns {
public static final String TABLE_NAME = "user";
public static final String COLUMN_NAME_TOKEN = "token";
}
Related
I'm making an app to insert data. But when I click on add button by giving all the details. App return me to previous page
This is the way I create insert class
public class InsertStudent extends AppCompatActivity {
Button instudent;
DBHelper dbHelper;
EditText sName,sDOB,sAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_student);
instudent = findViewById(R.id.btninsert);
sName = findViewById(R.id.insertname);
sDOB = findViewById(R.id.insertdob)
;
sAddress = findViewById(R.id.insertaddress);
Below is the way I coded to insert data
instudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userName = sName.getText().toString();
String dateB = sDOB.getText().toString();
String addr = sAddress.getText().toString();
boolean count = dbHelper.addInfo(userName,dateB,addr );
if(count =true){
Toast.makeText(InsertStudent.this, "Inserted!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(InsertStudent.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
});
This is addinfo method in DBHelper class
public boolean addInfo(String stdName, String stdDOB, String stdAddress){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(UserProfile.Users.COLUMN_STDNAME, stdName);
contentValues.put(UserProfile.Users.COLUMN_DATEOFBIRTH, stdDOB);
contentValues.put(UserProfile.Users.TABLE_ADDRESS, stdAddress);
long result = sqLiteDatabase.insert(UserProfile.Users.TABLE_NAME, null, contentValues);
if(result==1)
return false;
else
return true;
}
}
The insert method of "SQLiteDatabase" class doesn't return the
count, it's returns the id of the inserted row. so you are checking
if return result is 1, it's a true process, but it's not a way to
check the insert method. It means you need to check if there is any
return result, your insert action performed successfully, but if
there is a problem, the application will crash.
Make sure you created the table that you want to insert data in it.
Android Question?
I get json value and set on recyclerView ,How can make condition if i select item name then only print regarding this data value like Rate, amount like this.
Example: online ordering food android app
When you want to parse JSON , first you have to study about JSON Parsing.
You can Parse JSON by Volley Library , Retrofit etc.
Site to convert JSON to POJO/Model class jsonschema2pojo
Steps to Parse JSON :
Create Pojo class according to your json.
Using Volley or Retrofit to parse the json.
After setting data on pojo send the ArrayList to Recyclerview Adapter class.
You can also use GSON , its easy to parse json and set data to pojo classes.
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<ItemObject> posts = new ArrayList<ItemObject>();
posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
recyclerView.setAdapter(adapter);
Below is the tutorial to Json Parsing using Volley Library and set to RecyclerView .
Reference : https://inducesmile.com/android/android-json-parsing-using-gson-and-recyclerview/
How can make condition if i select item name then only print regarding
this data value like Rate, amount like this.
Ans : By position you can get the values of rate, amount on that position data on Recyclerview Adapter class.
How to pass all recyclerView data to next activity and save sqlite database in android, inside onclick Listener ?
When you want to send recyclerView Data to next Activity, you have to send the pojo class object to next activity by intent.
RecyclerView Data send to next Activity :
takeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Data send to next Activity
Intent intent = new Intent(HomeActivity.this,TakeSingleScanActivity.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)cList);
intent.putExtra("BUNDLE",args);
startActivity(intent);
}
});
RecyclerView Data Receive from Last Activity :
ArrayList<LoadDataResult> inList; //Global Variable
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
inList = (ArrayList<LoadDataResult>) args.getSerializable("ARRAYLIST");
Don't forget to implements your pojo class as Serializable :
public class LoadDataResult implements Serializable{
Create a loop to store all recyclerview data on Sqlite on your Activity Class :
for(int m = 0;m<mList.get(0).getResult().size();m++) {
callDataBaseHelper(mList.get(0).getResult().get(m).getName().trim(),
mList.get(0).getResult().get(m).getSku().trim(),
mList.get(0).getResult().get(m).getUpc().trim(),
mList.get(0).getResult().get(m).getPrice().trim(),
mList.get(0).getResult().get(m).getDisplaySize().trim(),
mList.get(0).getResult().get(m).getDisplaySizeYes(),
mList.get(0).getResult().get(m).getStatus().trim());
if(m == mList.get(0).getResult().size()-1) {
setData();
getRefreshTime();
utils.showtoast("Data Load Successful");
utils.hideDialog();
}
}
call DataBaseHelper class addData method :
private void callDataBaseHelper(String name, String sku, String upc, String price, String displaySize, int displaySizeYes, String status) {
boolean insertData = databaseHelper.addData(name,sku,upc,price,displaySize,displaySizeYes,status);
// if(insertData){
// Log.e("Inserted","Inserted ");
// }else{
// Log.e("NotInserted","NotInserted ");
// }
}
Create DataBaseHelper Class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "GiftsDatabase.db";
SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null,Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
String createTable = " CREATE TABLE "+ Constants.TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, "+Constants.NAME+" TEXT, "+Constants.SKU+" TEXT ,"+Constants.UPC+" TEXT,"+Constants.PRICE+" TEXT, "+Constants.DISPLAY_SIZE+" TEXT, "+Constants.DISPLAY_SIZE_YES+" INTEGER , "+Constants.STATUS+" TEXT)";
db.execSQL(createTable);
String createTableCount = " CREATE TABLE "+ Constants.TABLE_NAME_COUNT +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, "+Constants.SKU_COUNT+" TEXT ,"+Constants.QUANTITY_COUNT+" TEXT)";
db.execSQL(createTableCount);
Log.e(TAG,"Created Database");
}catch (Exception e){
Log.e("EXCEPTION",""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS "+Constants.TABLE_NAME);
db.execSQL(" DROP TABLE IF EXISTS "+Constants.TABLE_NAME_COUNT);
onCreate(db);
}
public boolean addData(String name , String sku, String upc , String price, String displaySize, int displaySizeYes, String status){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.NAME, name );
contentValues.put(Constants.SKU, sku );
contentValues.put(Constants.UPC, upc );
contentValues.put(Constants.PRICE, price );
contentValues.put(Constants.DISPLAY_SIZE, displaySize );
contentValues.put(Constants.DISPLAY_SIZE_YES, displaySizeYes );
contentValues.put(Constants.STATUS, status );
long result = db.insert(Constants.TABLE_NAME,null,contentValues);
Log.e(TAG,""+upc+" Inserted");
if(result == -1) {
return false;
}else{
// Log.e(TAG,"value inserted");
return true;
}
}
Store Checked RecyclerView data on ArrayList in RecyclerView Adapter Class
ArrayList<YourPojoClass> data = new ArrayList<YourPojoClass>();
inside onBindViewHolder(); This is used for store data in checked rows.
holder.checkBox..setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
data.add(name.get(position).getText,address.get(position).getText)
}
});
Send data to next Activity : Create a button at bottom of the recyclerView by Your Activity , and you click on that button send data to next activity.
I am creating an android application which has 3 EditTexts.
Now when I close the app and return it, the value in EditText are gone and I have to return the values last entered.
How can I return those values entered by the user in EditText (On the press of a button) so that the user don't have to enter the whole text again and again on closing and responding of the app?
Providing the answer with the code will help a lot! Thanks.
Put this class in your project
public class SaveData {
private static final String EDIT1 = "edit1";
private static final String EDIT2 = "edit2";
private static final String EDIT3 = "edit3";
SharedPreferences pref;
Editor editor;
Context mContext;
// Shared pref mode
int PRIVATE_MODE = 0;
public SaveData(Context context) {
this.mContext = context;
// Sharedpref file name
final String PREF_NAME = mContext.getString(R.string.app_name) + "_pref";
pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getEditText1() {
return pref.getString(EDIT1, "");
}
public void setEditText1(String text) {
editor.putString(EDIT1, text);
editor.commit();
}
public String getEditText2() {
return pref.getString(EDIT2, "");
}
public void setEditText2(String text){
editor.putString(EDIT2, text);
editor.commit();
}
public String getEditText3() {
return pref.getString(EDIT3, "");
}
public void setEditText3(String text) {
editor.putString(EDIT3, text);
editor.commit();
}
}
Now in onCreate put this
SaveData saveData = new SaveData(this);
mEditText1.setText(saveData.getEditText1());
mEditText2.setText(saveData.getEditText2());
mEditText3.setText(saveData.getEditText3());
And in onPause
SaveData saveData = new SaveData(this);
saveData.setEditText1(mEditText1.getText()+"");
saveData.setEditText2(mEditText2.getText()+"");
saveData.setEditText3(mEditText3.getText()+"");
There are several ways to store data of this type, I would personally use a database table, especially if you are ready have a database as part of your application. If not consider writing and array of strings to file and reading it.
If you are looking at the Database option the do something like
// on create
String createTable = "CREATE TABLE texts (id INT NOT NULL,words TEXT)";
SQLiteDatabase db = MyDatabaseHelper.getDB(); // <- use the method you use to get a db.
db.exec(createTable);
db.close();
// on start up of your edit text activity
// create array of edit texts which you have initialized via their ids, it must be a member variable
EditText[] editTexts = new EditText[]{editText1,editText2,editText3};
SQLiteDatabase db;
String sql= "SELECT * from texts";
Cursor c = db.rawQuery(sql,null);
if(null !=c && c.moveToFirst())
{
for(int i = 0; i<c.getCount(); i++)
{
// get data from db
String text = c.getString(1);
int id = c.getInt(0);
editTexts[id].setText(text);
}
}
// to be called at the end of the activity or when then edit texts change
private void saveToDb(){
SQLiteDataBase db; // got from your sqlite helper method
for(int i =0; i<editTexts.length; i++)
{
// check for insert
String check = "SELECT * FROM texts WHERE id ="+i;
String ins;
Cursor c = db.rawQuery(check,null);
if(null != c && c.moveToFirst()){
// update
ins= "UPDATE texts SET words = '"+editTexts[i].getText().toString+"' WHERE id = "+i+";";
}else{
// insert
ins = "INSERT into texts (id,words) VALUES("+i+",'"+editTexts[i].getText().toString+"');";
}
db.exec(ins);
db.close();
}
}
I have written this without testing it as a guide line, I have used this pattern many times before and it works well
I am developing an android app, and i want to display the primary key in the textview so that every-time I edit a textfield, I will be using the primary key to update.can anyone help me with this? below is the inserting of data in the sqlite. My problem is how to get the primary key...
public class UsedataActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
ImageButton evsave;
EditText evname;
EditText evtime;
EditText evdate;
EditText evcode;
TextView evadmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onetoone);
evsave = (ImageButton)findViewById(R.id.event_save);
evname = (EditText)findViewById(R.id.eventname);
evtime = (EditText)findViewById(R.id.time1);
evdate = (EditText)findViewById(R.id.eventdate);
evcode = (EditText)findViewById(R.id.eventcode);
evadmin = (TextView)findViewById(R.id.adminname_1to1);
evsave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Events addev =
new Events(evname.getText().toString(),evcode.getText().toString(),evdate.getText().toString(),Integer.parseInt(evtime.getText().toString()),evadmin.getText().toString());
db.addEvents(addev);
Toast.makeText(getApplicationContext(), "Event: "+ evname.getText()+" successfully save",
Toast.LENGTH_SHORT).show();
}
});
}
database handler class:
public void addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close();
}
As it can be observed from the docs for the SQLiteDatabase, db.insert will return the id of the newly created object. Just make addEvents return it (instead of being `void).
PS: Please paste code in edits of the question, not in comments. In comments they really look awful!
EDIT
public long addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
long id = db.insert(TABLE_EVENTS, null, values);
db.close();
return id;
}
And then:
long id = db.addEvents(addev);
Toast.makeText(getApplicationContext(),
"Event with id: "+ id + " successfully saved",
Toast.LENGTH_SHORT).show();
I wonder if someone could show me the error of my ways--I've been struggling with this issue for two days, and realize it must be a fundamental error of initializing variables, but...that reflects the level of my java knowledge.
I'm getting a database result on a delimited string wherein each of the segments has "null" appended to it. It seems that no matter how I change the initialization...well, two days!
I'm declaring the following in the class heading area:
private String strListContent;
private SQLiteDatabase database;
private DatabaseHelper helper2 = new DatabaseHelper(this);
private static final String fields[] = { "_id", "listTitle", "listType",
"listContent", "dateCreated", "dateModified" };
private ArrayList<String> textArray = new ArrayList<String>();
private ArrayList<Integer> imageArray = new ArrayList<Integer>();
Then concatenating my items in
final ImageButton addItem = (ImageButton) findViewById(R.id.btnToAddItem);
addItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemEdit = (EditText) findViewById(R.id.editTextItem);
if (itemEdit.getText().toString().equals("")) {
showToastMessage("Please enter an item to add...");
} else {
String newListItem = itemEdit.getText().toString();
strListContent += newListItem + "|~|";
...
}}}
I'm using the following bare-bones SQLiteOpenHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, "Cursor", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS list_data ("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, listTitle TEXT, listType TEXT, listContent TEXT, dateCreated TEXT, dateModified TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Steps to upgrade the database for the new version ...
}
}
To insert the values as so:
ImageButton saveAndBack = (ImageButton) findViewById(R.id.btnSaveBack);
saveAndBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String title = null;
String listContent = null;
Calendar javaCalendar = null;
title = titleEdit.getText().toString();
title = (title=="" || title==null)?"Untitled List":title;
strListContent = (strListContent=="" || strListContent==null)?"No Items|~|":strListContent;
listContent = strListContent;
String type = "R"; //"Regular List"
javaCalendar = Calendar.getInstance();
String currentDate = javaCalendar.get(Calendar.MONTH) + "/" + (javaCalendar.get(Calendar.DATE) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
database = helper2.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("listTitle", title);
values.put("listType", type);
values.put("listContent", listContent);
values.put("dateCreated", currentDate);
values.put("dateModified", currentDate);
database.insert("list_data", null, values);
Intent i = new Intent(RegularList.this, ActivityMain.class);
startActivity(i);
}
});
}
//
//End of OnCreate(){}
//
Then, when I retrieve from another activity:
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("list_data", fields, null, null, null,
null, null);
Integer tindex = data.getColumnIndex("listTitle");
Integer iindex = data.getColumnIndex("listType");
Integer cindex = data.getColumnIndex("listContent");
itemCount = 0;
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
showToastMessage(data.getString(cindex));
titleArrayList.add(data.getString(tindex));
if (data.getString(iindex) == "R") {
imageArrayList.add(R.drawable.listview_regular);
} else if (data.getString(iindex) == "L") {
imageArrayList.add(R.drawable.listview_location);
} else {
imageArrayList.add(R.drawable.listview_regular);
}
itemCount++;
}
data.close();
...
I can see in the toast message that each item from the delimited string has "null" appended to the front of it...the other values are fine. I hope this hasn't been too verbose, but...any recommendations? Thanks!
To me it looks like you may have simply not initialised the String strListContent before you first append to it with:
strListContent += newListItem + "|~|";
When you do that, you'll get a "null" prefixed in front of the value you are trying to append, just as you observe.
Perhaps you can just initialise in the declaration:
private String strListContent = "";