I have the default ParseUser class "User". The problem is that when I am trying to insert data into a new column in that class "updatePOST" using querying but it does not update.
That column shows "undefined". Plus I want that column "updatePOST" to hold only the latest string. I have also tried giving manually the objectId but noting happens.
Here is the code
public class ChangeAccount extends AppCompatActivity {
private ImageView imageView;
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_account);
imageView = (ImageView) findViewById(R.id.profile_pic_change);
editText = (EditText) findViewById(R.id.changeUpdatePost);
button = (Button) findViewById(R.id.change_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ParseUser currentUser = ParseUser.getCurrentUser();
String objectId = currentUser.getObjectId();
final String updatePost = editText.getText().toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
query.getInBackground((String) objectId, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if(e == null){
parseObject.put("updatePOST",updatePost);
parseObject.saveInBackground();
}
}
});
Intent i = new Intent(ChangeAccount.this,Account.class);
startActivity(i);
}
});
}
I have created a new "Update" class. And have put data in it. Also the above query is working fine for that class. The values are updating. So basically only the problem is with the default User class.
Any help will be appreciated. Thanks
I ran into a similar issue with the Installation object. Can you try adding the column into the User table in the parse dashboard? Creating that new data column along with the right data type worked for me.
**Update 5/4/16 **
Once you get the current ParseUser from ParseUser.getCurrentUser() you can immediately put key/value pairs on ParseUser. You don't need to construct another ParseQuery to get the User object. Please see the put method in the reference docs. Once you've set the desired key/value pair, you can then call saveInBackground() right away.
Related
I got the problem with adding new objects to Realm data base.
I have Product class extended Realm Object and my main code in Main Activity. When I launch the app without
Product product1 = myRealm.createObject(Product.class);
the entered objects are adds (appears on the screen) to Realm List and they disappears when I go to another activity (also a problem but not the case).
I see the reference on that string of code in Logcat. "java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction. "
product is also a string, so now you understand what means
setProduct.
I also have problems when I add
myRealm.commitTransaction()
or something.
public class MainActivity extends AppCompatActivity {
static View view1;
EditText editText;
static RealmList<Product> productRealmList;
static Realm myRealm = Realm.getDefaultInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Product TV = new Product("TV");
Product watch = new Product("Watch");
productRealmList = new RealmList<>();
productRealmList.add(TV);
productRealmList.add(watch);
MyAdapter adapter = new MyAdapter(this, R.layout.adapter_layout, productRealmList);
listView.setAdapter(adapter);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.alert_layout, null);
editText = view1.findViewById(R.id.ent);
new AlertDialog.Builder(MainActivity.this)
.setTitle("Create new product")
.setMessage("Put down the name of the new product")
.setView(view1)
.setNegativeButton("Cancel", null)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Product product1 = myRealm.createObject(Product.class);
product1.setProduct(editText.getText().toString());
productRealmList.add(product1);
}
})
.create()
.show();
}
});
I want to save the products to data base and RealmList when user enters the name of his/her product(s) and presses Add in Alert Dialog. (want them to be displayed on the screen)
You need to create your RealmObject inside a transaction as the exception also tells you.
Have a look at: https://realm.io/docs/java/latest/#transaction-blocks
Inside your OnClickListener do this:
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
final Product product1 = myRealm.createObject(Product.class);
product1.setProduct(editText.getText().toString());
productRealmList.add(product1);
}
});
You might have to create your productRealmList inside a transaction as well or at least fetch it from Realm inside your transaction block, but it's a bit difficult for me to test without creating a whole new project with Realm in.
My app doesn't display anything when passing data from one class to another. I located through with the debugger that my ArrayList doesn't get the right value from the class.
I'm sending data with the following function:
public class Adaugare extends AppCompatActivity {
private ListView myListView;
private NumeAdapter numeAdapter;
String inume;
int ivarsta;
Intent intent = new Intent();
private ArrayList persoanaArrayList = new ArrayList<>();
public ArrayList getPersoanaArrayList() {
return persoanaArrayList;
}
public int getPersoanaArrayListsize() {
return persoanaArrayList.size();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adaugare);
myListView = (ListView) findViewById(R.id.persoana_list);
Button btn_fin = (Button) findViewById(R.id.btn_fin);
btn_fin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText nume_edit_text = (EditText) findViewById(R.id.ins_nume);
EditText varsta_edit_text = (EditText) findViewById(R.id.ins_var);
ivarsta = Integer.parseInt(varsta_edit_text.getText().toString());
inume = nume_edit_text.getText().toString();
persoanaArrayList.add(new Persoana(inume, ivarsta));
}
});
}
}
And recieving it with:
public class Afisare extends AppCompatActivity {
ListView myListView;
NumeAdapter numeAdapter;
Adaugare ad = new Adaugare();
int cate;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afisare);
myListView = (ListView) findViewById(R.id.persoana_list);
ArrayList<Persoana> persoanaArrayList = new ArrayList<Persoana>(ad.getPersoanaArrayList());
numeAdapter = new NumeAdapter(this, persoanaArrayList);
myListView.setAdapter(numeAdapter);
}
The class Persoana is:
public class Persoana {
private String nume;
private int varsta;
Persoana(String inume, int ivar) {
this.nume = inume;
this.varsta = ivar;
}
public String getNume() {
return nume;
}
public int getVarsta() {
return varsta;
}
public void setNume(String nume) {
this.nume = nume;
}
public void setVarsta(int varsta) {
this.varsta = varsta;
}
}
Persoana is the main class, everything is saved in it. ad is an object of Adaugare, Adaugare being the class from which I've taken the code for getPersoanaArrayList. At debugging some values appeared at ad, namely Adaugare #4556, and persoanaArrayList remains null.
I need the persoanaArrayList so that i can initialize my Adapter and listView. Everything else in the code seems fine from step by step testing with debugger.
Your problem is with the following line in the Afisare class:
Adaugare ad = new Adaugare();
You can't simply new one activity from another activity and expect to access a shared list between them. To share instance data between java objects you need a reference to the other object. Creating a new instance will create a new empty list. That's why you are "losing" data. A quick fix would be to make the list static so it can be accessed from any instance.
But since you're dealing with Android, the right way to share data between activities is by using intent extras. The first activity starts the second activity via an intent. The first activity places the desired data in the intent as extras. The second activity uses getIntent() and the various methods on Intent to access the extras.
One last tip, in Android, you never use the new operator with Activities. Activities are created by the system to service an intent. If you find yourself using the new operator, that's a sign that you're doing something wrong.
I'm trying to create a diary where the users can write their diaries with a title and have it saved in the Firebase Database. The code should function as follows:
The user types in the title and the diary in the corresponding textviews and when "submit" is clicked, the information will be saved in the firebase database as a string. Later on I would like to also retrieve that data but for now, I'm just trying to get the data to save to the database. The app keeps crashing so I can't even get it to start.
Below is the java code:
public class draft extends AppCompatActivity {
TextView diary;
TextView titlee;
Button submit;
DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
diary = findViewById(R.id.Diary);
titlee = findViewById(R.id.Title);
submit = findViewById(R.id.Submit);
setContentView(R.layout.activity_draft);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = database.getReference("diary");
String fdiary =diary.getText().toString();
String ftitle =titlee.getText().toString();
String userId = mDatabase.push().getKey();
diaryclass userDiary = new diaryclass(ftitle,fdiary);
mDatabase.child(userId).setValue(userDiary);
}
});
}
}
and below is the diary class java file
public class diaryclass {
public String Title;
public String Diary;
public diaryclass(){
}
public diaryclass(String Title,String Diary){
this.Title=Title;
this.Diary=Diary;
}
}
below is a picture of the xml view so it is easier to imagine the view
Solved
using this modification the code now works
String diaryTitle = titlee.getText().toString();
String diaryContent = diary.getText().toString();
String userId = mDatabase.push().getKey();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Diary", diaryContent);
hashMap.put("Title", diaryTitle);
mDatabase.child(userId).setValue(hashMap);
titlee.setText("");
diary.setText("");
Why don't you try using HashMaps to push the values? You can do it like this:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = database.getReference("diary");
String fdiary =diary.getText().toString();
String ftitle =titlee.getText().toString();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Diary", fdiary);
hashMap.put("Title", ftitle);
mDatabase.push().setValue(hashMap);
}
});
This saves the values in the database. Now, underneath one branch of the database you will have Diary: fdiary and Title: ftitle. To retrieve those values you can use a ValueEventListener.
My Activity Login has edittext's value first entered by username and second value by password. I'm trying to pass this values of editText from Activity Class to nonActivityClass(Java Class).
Does exist any way to do this?
In MyLoginAcitivy:
yourButtonLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = yourEditTextUsername.getText().toString();
String password = yourEditTextPassword.getText().toString();
Intent intent = new Intent(this,nonActivityClass.class);
intent.putExtra("username",username);
intent.putExtra("password",password);
startActivity(intent);
}
});
In nonActivityClass:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAY_OUT);
Intent intent = getIntent();
if(intent != null){
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
}
}
I do not know why you want to do that. But you can do this using Preferences.
At your Activity save your data to Pref and load them at your Class
It depends on what you want to do with the data, I'm not sure what your issue is. You can use a Class with a Static method which can accept username and passwords then do your checking there or what ever operation you want after which you can return the result. There are other options to try out. Just like database classes which are not 'Activity classes', you can also pass values to them.
As in any normal class in Java with constructors:
User newuser = new User(uname, pwd); // in your activity
// in your class
public User(String uname,String pwd){
this.uname = uname;
this.pwd = pwd;
}
Please also consider to learn java basics before use it in android.
I'm trying to save two values from an activity (where the user can put in two different values, one String value and one integer value) in the listview from another activity. In the first activity, it shows a list with a course and the amount of points for that course in one listview, like this:
Course: English
Points: 4
Now, the problem is, everytime I want to put in another value using the add_course_actitivty, it overwrites the previous value. I've looked at different solutions, like with sharedpreferences (Add items to listview from other activity), but this uses only one value and if I try to work with sharedpreferences, it overwrites the other value in the sharedpreferences, but I want users to add multiple courses and corresponding points. Also on restart, it deletes the values in the listview (I read to prevent this you need to store it in sharedpreferences, but this doesn't work the way I need it to be)
KeuzeActivity.class (shows the listview):
public class KeuzeActivity extends AppCompatActivity {
private FloatingActionButton fab_add;
private String student_naam;
private ListView keuze_list;
boolean wantDelete;
private ArrayAdapter adapter;
private String vak;
private int ec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keuze);
// setting title
student_naam = getIntent().getStringExtra("student");
setTitle("Keuzevakken en projecten van " + student_naam);
//initialzing elements
fab_add = (FloatingActionButton)findViewById(R.id.fab_add);
keuze_list = (ListView) findViewById(R.id.keuze_list);
//initializing list
final ArrayList<Course> courseItems = new ArrayList<Course>();
adapter = new ArrayAdapter<Course>(this, android.R.layout.simple_list_item_1, courseItems);
keuze_list.setAdapter(adapter);
// checks if intent has required values, put it in listview
if (getIntent().hasExtra("vak") && getIntent().hasExtra("ec")) {
vak = getIntent().getStringExtra("vak");
ec = getIntent().getIntExtra("ec", ec);
courseItems.add(new Course(vak, ec));
adapter.notifyDataSetChanged();
}
// make fab go to other activity
fab_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(KeuzeActivity.this, add_course_activity.class));
}
});
// long press deletes item
keuze_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
showDeleteDialog();
if (wantDelete) {
courseItems.remove(position);
adapter.notifyDataSetChanged();
}
return true;
}
});
}
private void showDeleteDialog() {
AlertDialog.Builder infobuilder = new AlertDialog.Builder(this);
infobuilder.setCancelable(false);
infobuilder.setTitle("Vak/project verwijderen");
infobuilder.setMessage("Weet je zeker dat je het vak of project wilt verwijderen?");
final TextView text = new TextView(this);
// action when pressed OK
infobuilder.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
wantDelete = true;
dialog.cancel();
}
});
infobuilder.setNegativeButton("Nee", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
wantDelete = false;
dialog.cancel();
}
});
infobuilder.show();
}
}
add_course_activity.class (let's users input course and points)
public class add_course_activity extends AppCompatActivity {
private EditText course_edit;
private EditText ec_edit;
private Button save_btn;
private String student_name;
private int ec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
setTitle("Voeg vak of project toe");
final Context context = getApplicationContext();
// initializing elements
course_edit = (EditText) findViewById(R.id.edit_vak);
ec_edit = (EditText) findViewById(R.id.edit_ec);
save_btn = (Button) findViewById(R.id.save_button);
// action on savebutton
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (course_edit.getText().toString().trim().length() > 0 && ec_edit.getText().toString().trim().length() > 0 ) {
ec = Integer.parseInt(ec_edit.getText().toString());
Intent goBack = new Intent(add_course_activity.this, KeuzeActivity.class);
goBack.putExtra("vak", course_edit.getText().toString());
goBack.putExtra("ec", ec);
goBack.putExtra("student", PreferenceManager.getDefaultSharedPreferences(context).getString("student_name", student_name));
startActivity(goBack);
}
else {
Toast.makeText(context, "Voer juiste informatie in!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Course.java class (getters and setters + with toString method)
public class Course {
private String vak;
private int ec;
public Course(String vak, int ec) {
this.vak = vak;
this.ec = ec;
}
public String getVak() {
return vak;
}
public void setVak(String vak) {
this.vak = vak;
}
public int getEc() {
return ec;
}
public void setEc(int ec) {
this.ec = ec;
}
#Override
public String toString() {
return ("Vak: " + vak + "\n" + "Punten: " + ec);
}
}
Note that my code isn't clean or done, but to get further I need to fix this problem.
You have several way to do it. As other replies have suggested you can use an SQLLite database and add data to a course table and retrieve data from it.
If you find Db approach to complicated/heavy
You could also use SharedPreferences what you need to do is figure a way to store a string that represent a list of course. It is not the best way to approach it but it will work.
Lets say you choose to serialize your Course object with "vac-ec"
Then you just store a serialized list of course. Example "vac1-ec1,vac2-ec2"
When you need to add a course you juste grab the previous string split it to list, append the new course to the list and re-serialize the list to a string to encode it.
Other solution could be to use Realm.
You should used SQLiteDatabase and create a table with valid attributes and insert your new values into them
Okay, now things are clearer. As answered by #Dwijraj, when storing what potentially will be a large set of data, for maximum control it is best to use SQLite.
You can read more about the different Saving Data methods here:
https://developer.android.com/training/basics/data-storage/index.html
SharedPreferences are best used to store small amounts of information, like storing the settings of an application. [Mute] for example. Or a highscore in case of a game.
A Database is a better option when it comes to storing large pieces of data that you will potentially manipulate.
Your data structure can be something like this, Courses table containing Unique_ID , Course Name, Course Level, Course summary.
A table for English for example which will contain
Exams, Scores, Duration.
There are a lot of things you can do.
Try by storing the records in SQLite, and get it when you want to show.
By this, You can have a track of all added items. And you can show the items you want.