I'm using this code to actually let the user send a questionand 4 answers (it's a long story), and storage it on my game database. This is the code I used, after seeing the docs and just the table doesn't get updated. I don't really know why
private void sendQuestion() {
ParseUser currentUser = ParseUser.getCurrentUser();
String role = currentUser.get("Role").toString();
if(role.equals("Founder"))
{
String questionText = mQuestion.getText().toString();
String[] answers = new String[4];
for(int i = 0; i < 4; i++) {
answers[i] = mAnswers[i].getText().toString();
}
ParseObject question = new ParseObject("Questions");
question.put("lang", mSelectedLang);
question.put("question", questionText);
for(int i = 0; i < 4; i++) question.put("answer" + (i+1), answers[i]);
question.put("enabled", true);
question.put("from", currentUser);
question.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.d("MyApp", "Done");
}
});
}else
Log.d("MyApp", "Not founder");
}
This is what I get from the Logs
05-27 19:57:21.063 2307-2307/*************** D/MyApp﹕ Send question button pressed
05-27 19:57:21.530 2307-2307/*************** D/MyApp﹕ Done
Says it's done but the Table Questions is not updated, as said. Pay attention that both "lang" and "from" are relations fields, so I put there object and not simple values like Strings or Integer.
Why doesn't the table get updated?
Here you can look the official docs to save an object https://www.parse.com/docs/android/guide#objects-saving-objects
I self resolved changing the rows type from 'Relation' to 'Pointer', as I read here https://parse.com/questions/expected-relation_user-but-got-_user (didn't find it because it was asked for iOS but it's not about the wrong code).
Now it works.
I think you should change
question.put("from", currentUser);
with something like:
question.put("from", currentUser.getId()); // pass id of user, not object itself
Related
I'm creating a Quiz app in Android Studio, and so I created a Database that contains the questions. In the helper class I have a method getAllQuestions that transfers the questions from the database to an array list, so then I can extract the Questions in Main and setText in Buttons. However, while I run my app the buttons and the Question are empty, without the app throwing exceptions like nullpointer if the list itself was empty.
DB_Helper methods:
private void addQuestions(QuestionsDataBase Questions)
{
ContentValues cv = new ContentValues();
cv.put(QuestionTable.Column_Question,Questions.getQuestion());
cv.put(QuestionTable.Column_Option1,Questions.getOption1());
cv.put(QuestionTable.Column_Option2,Questions.getOption2());
cv.put(QuestionTable.Column_Option3,Questions.getOption3());
cv.put(QuestionTable.Column_Option4,Questions.getOption4());
cv.put(QuestionTable.Column_Correct_Ans,Questions.getQuestion());
db.insert(QuestionTable.Table_Name,null,cv);
}
public ArrayList getAllQuestions(){
ArrayList<QuestionsDataBase> questionsList = new ArrayList<>();
db = getReadableDatabase();
String[] Projection ={
QuestionTable._ID,
QuestionTable.Column_Question,
QuestionTable.Column_Option1,
QuestionTable.Column_Option2,
QuestionTable.Column_Option3,
QuestionTable.Column_Option4,
QuestionTable.Column_Correct_Ans
};
Cursor c = db.query(QuestionTable.Table_Name,
Projection,
null,
null,
null,
null,
null);
if(c.moveToFirst()){
do{
QuestionsDataBase questions = new QuestionsDataBase();
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Question)));
questions.setOption1(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option1)));
questions.setOption2(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option2)));
questions.setOption3(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option3)));
questions.setOption4(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option4)));
questions.setCorrectAns(c.getInt(c.getColumnIndexOrThrow(QuestionTable.Column_Correct_Ans)));
questionsList.add(questions);
questionsList.add(questions);
}while(c.moveToNext());
}
c.close();
return questionsList;
}
Methods in MainActivity:
private void fecthDB(){
DB_Helper db = new DB_Helper(this);
questionList = db.getAllQuestions();
startQuiz();
}
private void startQuiz()
{
questionTotalCount = questionList.size(); // the total amount of questions in the current quizactivity( is set to 10)
Collections.shuffle(questionList); // shuffle the questions form the database that are stored in QuestionList
showQuestions();
nextbutton.setOnClickListener(view -> {
if(!answered){
if(option1.isChecked() || option2.isChecked() || option3.isChecked() || option4.isChecked())
QuizOperations();
}
});
}
private void showQuestions() // Showing the question and the options from database
{
rbGroup.clearCheck();
if(questionCounter< questionTotalCount) // if not all the questions yet answered set text to new questions
{
currentQuestions = questionList.get(questionCounter);
questionCount.setText(currentQuestions.getQuestion());
option1.setText(currentQuestions.getOption1());
option2.setText(currentQuestions.getOption2());
option3.setText(currentQuestions.getOption3());
option4.setText(currentQuestions.getOption4());
questionCounter ++; // +1 to question counter
answered = false; // tye quiz is not yet completely answered while the current question is smaller then total
nextbutton.setText("Next");
questionCount.setText("Questions: " + questionCounter + "/" + questionTotalCount); // how many questions answered out of 10
}
else{// if all the questions are answered
handler.postDelayed(() -> {
Intent intent = new Intent(getApplicationContext(),QuizActivity.class); // open the next activity
}, 500); // wait for a half second
}
}
I believe you want to set other fields on your QuestionsDataBase object here rather than setQuestion() for each column in the database query:
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option1)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option2)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option3)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option4)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Correct_Ans)));
Thanks, edited it. Now it shows the options, but doesn't show the question itself.
You are setting text to questionCount twice where the later overwrites the first one. Maybe the first one should set the question textview instead.
I have an android program that passes 2 value to mySQL, that is Time in and Time out. I don`t know what happen but I have a scenario that the data passed is incomplete. For example i will create a record and the only need to put is time in after i type the time i will click save so the record is time in has a data and time out is null. After saving, my auto passer sends that data to mySQL. The next thing I will do is to edit that record to add Time Out so both of them has a data. auto passer will run after checking to my database my both of columns has a data. Now this is where the error begins, I have a button call refresh which will retrieve my data from mySQL,create a JSON of that then send it in my android after the process the returned data has no Time Out and when i check it the data in mySQL has no time out also even i add it. I dont know what happened
What I did in my Java is to create a JSONArray the convert it to string the pass it in my php file then my php file decodes it then loop it while saving to database.
This is how i create a json
JSONArray vis_array = new JSONArray();
Cursor unsync_vis = Sync.Unsync_Visit_All();
while (unsync_vis.moveToNext()) {
JSONObject vis_data = new JSONObject();
try {
vis_data.put("t1", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t1"))));
vis_data.put("t2", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t2"))));
vis_array.put(vis_data);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Auto Sync Error", e.getMessage());
}
}
public String formatInsert_n(String data) {
if (TextUtils.isEmpty(data) || data.length() == 0) {
data = "null";
} else {
data = data.replace("'", "''");
data = data.replace("null", "");
if (data.toString().matches("")) {
data = "null";
} else {
data = "'" + data + "'";
}
}
return data;
}
after creating that json, i will convert it to string the pass it using stringRequest then in my php i will decode it use for loop the save it in mySQL
Here is the php code
<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$insert_visit_new = isset($_POST['insert_visit_new']) ? $_POST['insert_visit_new'] : "";
if ($insert_visit_new != "") {
$vis_array = json_decode($insert_visit_new, true);
$vis_count = count($vis_array);
for ($i = 0; $i < $vis_count; $i++) {
$vis = $vis_array[$i];
$t1 = $vis['t1'];
$t2 = $vis['t2'];
$ins_sql = "INSERT INTO table t1,t2 VALUES ('$t1','$t2') ON DUPLICATE KEY UPDATE t1 = $t1,t2 = $t2"
$stmt = $DB->prepare($ins_sql);
$stmt->execute();
}
}
echo "done";
?>
by the way the code above is inside an AsyncTask and the class is a BroadcastReceiver
is the cause is i dont unregister my BroadcastReceiver?
or my jsonArray name from this class and inside my refresh button are same?
my question is whats wrong? looks like it still passes the old data. any help is appreciated TYSM
I have a json array of all names and contacts on my phone, looks something like this:
[{"name":"andy","phone_number":"+123"},{"name":"bob","phone_number":"+456"},{"name":"chris","phone_number":"+789"}]
I check the phone numbers against phone numbers in a db, if there's a match I want to show the name in the recycler view, if no match, then show just the number.
For example, +123, yes, it is in the db, so show andy in the cell in recyclerview. +789 is not in the db, so show +789 in the cell.
Here's what I'm working with so far: it works when there is a match, the if part, but I don't know how to deal with the else part (for when there is no match). If I uncomment my else code it always jumps straight to there.
public void onResponse(String response) {
try {
//name our JSONObject User_Private_Public_Obj, which is response from server
//the response from server will be like:
//{"private_review_ids":[{"reviewid":7,"username":"+123"},{"reviewid":14,"username":"+456"}]}
JSONObject User_Private_Public_Obj = new JSONObject(response);
//Now break up the response from server
//We want the JSON Array part, "private_review_ids"
JSONArray private_ids = User_Private_Public_Obj.getJSONArray("private_review_ids");
for
//get the number of objects in User_Private_Public_Obj
(int i = 0; i < private_ids.length(); i++)
{
//for each object in the array private_ids, name it obj
//each obj will consist of reviewid and username
JSONObject obj = private_ids.getJSONObject(i);
Review review = new Review();
//get the string from sharedpreferences, AllPhonesandNamesofContacts,
//it will be like [{"phone_number":"+123","name":"andy"}, etc...]
//we want this so we can display phone name in recyclerView, if it's a contact
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("AllPhonesandNamesofContacts", "0");
//convert the string above into a json array
JSONArray jsonArray = new JSONArray(json_array);
//set a string to the phone number from the DB,
//the phone number of the person who made the review
phoneNoInDB = obj.getString("username");
//set the setter to the phone number string, the string is
//the phone number of the person who made the review
review.setPhoneNumberofUserFromDB(phoneNoInDB);
//jsonArray is our All Phones and Names of Contacts array
int matching = jsonArray.length();
for (int n = 0; n < matching; n++) {
try {
//for every object in "All Phones and Names of Contacts" array...
JSONObject object = jsonArray.getJSONObject(n);
//if the review maker is a contact...that is,
//if the phone_number in AllPhonesandNamesofContacts equals
//the phone number in the DB
if (object.getString("phone_number").equals(phoneNoInDB)) {
//just for testing purposes...
Toast.makeText(NewActivity.this, object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
//then rip out the other part of the object, the name in
// AllPhonesandNamesofContacts
//of the person who made the review
review.setphoneNameonPhone(object.getString("name"));
//add the review to the sharedReviewList
reviewList.add(review);
}
/* else {
//just for testing...
Toast.makeText(NewActivity.this, " should be green" + object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
review.setphoneNameonPhone(object.getString("phone_number"));
//add the review to the sharedReviewList
//reviewList.add(review);
}*/
} catch (JSONException e) {
System.out.println("error in if else");
//Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//set the adapter to show the random reviews
recyclerView.setAdapter(uAdapter);
before voting down please read my question , which I have searched a lot but I couldn't find the answer yet, so I would appreciate if you give me hand to overcome the problem.
Actually I need to update a tuple in a table named "Demographics". But it seems my code does not work correctly, and in fact after running the app , I got the result "0" for updating which means nothing get updated.
12-21 12:34:54.190 2351-2367/? D/Update Result:: =0
I guess my problem is due to not pointing to the right row of the table based on Primary key. Actually when a user Register to my app the following things should happen:
1- Create a tuple in "Demographics" table --> username, password and email will be inserted. An auto increment primary key also constructed and inserted.
2- user logins , then he can complete rest of information in "Demographics" table. --> this MODIFICATION is the "update" process which I', asking.
Would you please tell me if the following codes are wrong or have any implicit error?
DemographicsCRUD.java
public long UpdateDemographics(Demographics_to demoId) {
//SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DataBaseHelper.lastName, demoId.getD_lastName());
values.put(DataBaseHelper.firstName, demoId.getD_firstName());
values.put(DataBaseHelper.dateOfBirth, demoId.getD_dateOfBirth())
long result = database.update(dbHelper.Demographics_Table, values,
WHERE_ID_EQUALS,
new String[]{String.valueOf(demoId.getD_patientID())});
Log.d("Update Result:", "=" + result);
// db.close();
return result;
}
here is where I call the above code:
private void updateDemographicsTable()
{
ep_demoId = new Demographics_to();
String ep_na = ep_name.getText().toString();
String ep_fa = ep_family.getText().toString();
.
.
.
ep_demoId.setD_dateOfBirth(ep_bd);
ep_demoId.setD_firstName(ep_na);
ep_demoId.setD_lastName(ep_fa);
}
#Override
protected Long doInBackground(Void... arg0) {
long result = ep_demoCRUD.UpdateDemographics(ep_demoId);
return result;
}
#Override
protected void onPostExecute(Long result) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Information Updated!",
Toast.LENGTH_LONG).show();
}}
Looks like whatever you are passing in as the patientID does not have a matching record in the database or the dataobject "Demographics_to" has the patient ID set incorrectly.
I need some guidance on my current obstacle with this application. If you can point me in the right direction will help. Basically I have twitter like application with a sql database storing the "tweets" and the users data.The user's nickname always start with a "#". Now everything is working but i need to add the functionality that if I send a twit and "mentioned" a user, meaning I add #nickname , then that person I mentioned should see it on his messages. I think I can figure it out, but i'm just confused on how to get started, specifically when I'm getting the "tweet" how can I find a "#" and return the word that contains the "#" ? The next step should probably be to see if that nickname exists and find the userID by the nickname and update their messages? Please help me out.
This is what I'm trying.. not working..
HttpSession session = request.getSession();
String tweet = request.getParameter("tweet");
ArrayList<User> x= new ArrayList<User>();
for(int i = 0; i < x.size(); i++){
String alias = x.get(i).getAlias();
if(tweet.contains(alias)){
try {
int uid= getUseridByNickName(alias);
Twit t = new Twit();
t.setMentionedUserID(uid);
} catch (SQLException ex) {
Logger.getLogger(TwitServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
To get the username of the mentioned users you could simply use the indexOf method:
String s = "#user1 #user2 some text";
ArrayList<String> users = new ArrayList<>();
int index = s.indexOf("#");
while(index != -1) {
users.add(s.substring(index + 1, s.indexOf(" ", index)));
index = s.indexOf("#", index + 1);
}
users.stream().forEach(System.out::println);
Note that this method will work only if the username is followed by a space, otherwise the username will also contain the text between the "#" and the first space it founds (e.g. the tweet "#user1, some text" will return "user1,")