I have 3 activities - login activity, main page activity, profile activity. The login activity will call main page activity and main page activity will call profile activity. How can I pass the data from login activity to profile activity? Is it must pass the data from login activity to main page activity first then pass to profile activity from main page activity? Or is there any other way to pass the data? Thanks!
You can do that... or you could store the data in a persistent storage and read back whenever required.
Learn about SharedPreferences here - Saving Key-Value Sets | SharedPreferences
Saving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Retrieving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Learn about SQLite Database here - Saving Data in SQL Databases | SQLite Database
Saving data looks like:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
Retrieving data looks like:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
List itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedEntry._ID));
itemIds.add(itemId);
}
cursor.close();
There are two methods to pass values between Activities in Android:
1. Using intent:
Example:
In the Login Activity, put the following code inside the OnClickListiner:
Intent intent = new Intent(getApplicationContext(), mainActivity.class);
intent.putExtra("username", usernameVariable);
intent.putExtra("password", passwordVariable);
startActivity(intent);
Then, on the mainActivity, to receive the values use the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String u = intent.getStringExtra("username");
String p = intent.getStringExtra("password");
// note: the arguments should match the same as its in the loginActivity
}
2. Using Static Variables:
Example:
On the LoginActivity, create two static attributes. Like the following:
Public Class LoginActivity{
public static String username;
public static String password;
protected void onCreate(Bundle savedInstanceState) {
...
}
}
Then, in the mainActivity class use the following code to get these values:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
String u=LoginActivity.username;
String p=LoginActivity.password;
}
Hope it solved your problem...
There is one more way that you can use create a singleton class and store the value and use it.
public final class ProfileDataModel {
private static ProfileDataModel instance;
private String userName;
private String address;
private ProfileDataModel() {
}
/**
* Get Instance for Profile
* #return
*/
public static ProfileDataModel getInstance() {
if (instance == null){
instance = new ProfileDataModel();
}
return instance;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
// Use cases
//Set the data
ProfileDataModel.getInstance().setAddress("Data from login response");
ProfileDataModel.getInstance().setUserName("As per request/response");
//Get the data
String address = ProfileDataModel.getInstance().getAddress();
String userName = ProfileDataModel.getInstance().getUserName();
Related
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 have this code where I'll get all the available rows with same DueDateTime
public List<DatabaseSource> getListSched() {
text = sharedPreference.getValue2(context);
String shareFact = text.toString();
List<DatabaseSource> schedList= new ArrayList<DatabaseSource>();
// Select All Query
String selectQuery = "SELECT * FROM schedTBL WHERE DueDateTime like " + shareFact;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
DatabaseSource sched= new DatabaseSource();
sched.setId(Integer.parseInt(cursor.getString(0)));
sched.setSubject(cursor.getString(1));
sched.setDescription(cursor.getString(2));
sched.setDueDateTime(cursor.getString(3));
// Adding sched to list
contactList.add(sched);
} while (cursor.moveToNext());
}
// return schedlist
return schedList;
}
Am I doing it right??, it seems I cannot use the sharedpreferences in it, I have SharedPreferencesUID Class, I store this code below to get the value wherever I want to
public String getValue2(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString("dateselected", null);
return text;
}
The only solution I could do is to MIGRATE getListSched to the activity where needs it (for specific activity only) then just call the DatabaseSched Class (which has the SQLiteOpenHelper) so I could use the sharedPreference.
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 have class called unviersityClient and method name `getallstudent,but how to include them in cursor to get results displayed
this is in mainactivity
public class MainActivity extends ActionBarActivity {
private TextView tv;
private Button bt;
private Context mycontext;
Cursor c;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
bt=(Button)findViewById(R.id.button1);
mycontext=this.getApplication();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// universityClient.addStudents(mycontext, "christy");
// universityClient.addStudents(mycontext, "joe");
universityClient.getAllStudents(mycontext);
c.moveToFirst();
while(!c.isAfterLast()){
String dir =c.getString(c.getColumnIndex("name"));
tv.setText("Name : "+dir);
c.moveToNext();
}
and this is in .java created by json. it's already created the db
public static Cursor getAllStudents(Context c) {
ContentResolver cr = c.getContentResolver();
String[] result_columns = new String[]{
universityDB.STUDENTS__ID_COLUMN,
universityDB.STUDENTS_NAME_COLUMN,
};
String where = null;
String whereArgs[] = null;
String order = null;
Cursor resultCursor = cr.query(university.STUDENTS_URI, result_columns, where, whereArgs, order);
return resultCursor;
}
if you have all the students in a database you can use this to get all the names and then send them to a variable
String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
C1 = cursor.getString(cursor
.getColumnIndex("_id"));
C2 = cursor.getString(cursor
.getColumnIndex("name"));
Fin += C1 + "-" + C2 + "\n";
} while (cursor.moveToNext());
}
}
cursor.close();
Fin is a String and you can get all the names or whatever you want from the columns with the getColumnIndex("nameOfTheColumn") and send "Fin" to a textview or something like that
hope that helps!, see ya
Cant understand why you want to put json data in cursor while json parsing is the best way to do the same. If your priority is to bring data somewhere else and fetch one by one using loop, you can use arraylist/hashmap like collection objects. If you have many fields in one json object, you can create a class having those fields and make an arraylist of that having type of class and store data in that. Like this:
1. Fetch single json object at a time, fetch values of fields.
2. create class object by passing those values in constructor.
3. Create arraylist of that class type.
4. put class objects in that arraylist one by one and fetch as well.
ArrayList<Person> person = new ArrayList<Person>();
Person newPerson = new Person("balvier", "27", "Male");
person.add(newPerson);
Person newPersonAnother = new Person("Adel", "20", "FeMale");
person.add(newPersonAnother);
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";
}