Want to create new Record in QuickBlox Custom Table which allready created.
i have Follow the guideline Url and using below method, here i m using my Table name
HashMap<String, Object> fields = new HashMap<String, Object>();
fields.put("User ID",String.valueOf(myID));
fields.put("senderLoginID", ""+mylogin.toString());
fields.put("receiverLoginID", ""+friendLogin.toString());
fields.put("messages", messageString);
fields.put("isRead", false);
QBCustomObject qbCustomObject = new QBCustomObject();
qbCustomObject.setClassName("Movie"); // your Class name
qbCustomObject.setFields(fields);
QBCustomObjects.createObject(qbCustomObject, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBCustomObjectResult qbCustomObjectResult = (QBCustomObjectResult) result;
QBCustomObject qbCustomObject = qbCustomObjectResult.getCustomObject();
Log.d("New record: ",newCustomObject.toString());
} else {
Log.e("Errors",result.getErrors().toString());
}
}
});
Error getting Like
** '{"errors":{"base":["Forbidden. Need user."]}}'
… Request has been completed with error: [base Forbidden. Need user.]
1st off all, you don't need to use this
fields.put("User ID",String.valueOf(myID));
This field will be filled on the server based on your token information
Next, you have to be logged in in order to create record,
just do the next
http://quickblox.com/developers/SimpleSample-users-android#Sign_In_.26_Social_authorization
Related
I am trying to get some data from a databse using JSON, but debugging the app showed me that Value null at ID_UTILIZ of type org.json.JSONObject$1 cannot be converted to int . I have checked the database and the ID_UTILIZ column is set as Int . This activity is used for registering, and also storing the data for SharedPreferences, so I am using also a User class, but I have also set the Id at int there too. I cannot see what I am doing wrong
code:
class RegisterUser extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("nume", Nume);
params.put("email", Email);
params.put("Parola", Parola_cont);
params.put("prenume", Prenume);
params.put("telefon", Telefon);
params.put("departament", spinner);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_REGISTER, params);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("Nume"),
userJson.getString("Prenume"),
userJson.getString("Adresa_mail"),
userJson.getString("Numar_telefon"),
userJson.getString("Parola"),
userJson.getInt("ID_UTILIZ"),
userJson.getString("Departament")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//executing the async task
RegisterUser ru = new RegisterUser();
ru.execute();
}
php:
case 'inregistrare':
if(isTheseParametersAvailable(array('nume','email','Parola','prenume', 'telefon', 'departament'))){
$prenume = $_POST["prenume"];
$nume =$_POST["nume"];
$email =$_POST["email"];
$telefon =$_POST["telefon"];
$parola =md5($_POST["Parola"]);
$tip = 2;
$departament=$_POST["departament"];
$stmt = $conn->prepare("SELECT ID_UTILIZ FROM informatii_persoane WHERE Adresa_mail = ? OR Numar_telefon = ?");
$stmt->bind_param("ss", $email, $telefon);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
$response['error'] = true;
$response['message'] = 'Utilizator existent';
$stmt->close();
}else{
$stmt = $conn->prepare("INSERT INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon, Parola, Tip_utilizator, Departament) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssis", $nume, $prenume, $email, $telefon, $parola, $tip, $departament);
if($stmt->execute()){
$stmt = $conn->prepare("SELECT ID_UTILIZ, Nume, Prenume, Adresa_mail, Numar_telefon, Parola, Departament FROM informatii_persoane WHERE Adresa_mail = ?");
$stmt->bind_param("s",$Adresa_mail);
$stmt->execute();
$stmt->bind_result($id, $nume, $prenume, $email, $telefon, $parola, $departament);
$stmt->fetch();
$user = array(
'Nume'=>$nume,
'Prenume'=>$prenume,
'Adresa_mail'=>$email,
'Numar_telefon'=>$telefon,
'Parola'=>$parola,
'ID_UTILIZ'=>$id,
'Departament'=>$departament
);
$stmt->close();
$response['error'] = false;
$response['message'] = 'Utilizator inregistrat cu success';
$response['user'] = $user;
}
}
}else{
$response['error'] = true;
$response['message'] = 'A aparut o eroare';
}
break;
The registering process it's working, I have all the data stored in database and I can log in later, but because of the error mentioned above, the code stops and:
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
doesn't start the Home.class activity so my app stays on the same window. I have tried to search for other questions posted before, but none had a solution that worked. I think I am missing something, but I cannot see what. Thanks!
You can't not convert null to int. So, you have to check first your specific value is not null.
Try like this
int id_utiliz = -1; // set default value
// check ID_UTILIZ is not null and then get value.
if(!userJson.isNull("ID_UTILIZ")) {
id_utiliz = userJson.getInt("ID_UTILIZ");
}
//creating a new user object
User user = new User(
userJson.getString("Nume"),
userJson.getString("Prenume"),
userJson.getString("Adresa_mail"),
userJson.getString("Numar_telefon"),
userJson.getString("Parola"),
id_utiliz,
userJson.getString("Departament")
);
And Use finish() below the startActivity(...) like the following.
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
startActivity(new Intent(getApplicationContext(), Home.class));
finish(); // use this statement here.
You should make sure that ID_UTILIZ has any value defined, it should not be null. OR you can simply assign a default value to ID_UTILIZ in your table.
int primitive type doesn't accept null values, you can use the Integer wrapper class which can have a value of null, usually when serializing JSON object from network call i use wrapper class not primitives.
also use responseJsonObject.isNull(ID_UTILIZ) to check if object has no mapping for ID_UTILIZ or if it has a mapping whose value is NULL.
I am new to Kumulos development.
I want to get selected data from table of kumulos.
Like If user enter username and password i check from table that data exits or not.
But the issue is while checking data inserted in table and not giving me correct output.
While testing api in browser it works fine.
My code for select from table is below.
public void CallApiLogin(){
final String Uname=editUname.getText().toString();
final String pass=editPass.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", Uname);
params.put("password",pass);
Kumulos.call("user_register", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
// Do updates to UI/data models based on result
ArrayList<LinkedHashMap<String, Object>> objects = (ArrayList<LinkedHashMap<String,Object>>) result;
for (LinkedHashMap<String, Object> item : objects) {
String name = (String) item.get("name");
String password = (String) item.get("password");
if(name.equalsIgnoreCase(Uname) && password.equalsIgnoreCase(pass)){
Intent i=new Intent(Login.this,Home.class);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(),"Please enter valid username and password.",Toast.LENGTH_SHORT).show();
}
}
}
});
}
Please suggest where i am going wrong as requested data inserted in table.
But i want that request data exist or not????
After spending hours, I got solution.
Issue is creating api. In Kumulos you have to create different api.
I was using api "user_register", Now i have create other api call "Select_user".
This api works fine what the result i want.
I hope this question may help some other.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have an SQL Server Database with quotes.
The table has four fields ID primary key, Title, Description, and InsertDate.
I have created an Android application to display the quotes. The quotes are downloaded locally to the SQLite database and then displayed using ListView.
Whenever the user clicks the sync button, if any new quotes are added to the SQL Server database it should be downloaded to the SQLite database.
I have created a web service for the syncing using RestApi.
I have never used Webservice and new to Android development. Worked on Asp.net/C#.
My question is:
The android application should only download the latest records how to request only the latest inserted record from android using webservice.
If I change a record on SQL server how to identify such records and change in the SQLite database.
My current code is logically wrong and I need to change as it is deleting all the records and inserting all the records again. (Wanted to give demo to the customer)
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
client.get(getApplicationContext().getString(R.string.IpAdd) + "/WebApi/api/mpAudioapi/GetAllAudio", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
String str;
try {
str = new String(responseBody, "UTF-8");
} catch (UnsupportedEncodingException e) {
// this should never happen because "UTF-8" is hard-coded.
throw new IllegalStateException(e);
}
updateSQLite(str);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
The code to Sync
int writing_counts = dbHandler.getMpAudioRowCount();
ArrayList<HashMap<String, String>> usersynclist;
usersynclist = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
//JSONObject responseObject = new JSONObject(response);
//JSONArray arr = responseObject.getJSONArray("results");
//JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
if (writing_counts == arr.length()) {
Toast.makeText(getApplicationContext(), "Sorry. No new writings to sync.", Toast.LENGTH_LONG).show();
return;
}
dbHandler.truncateTableAudio();
// If no of array elements is not zero
if (arr.length() != 0) {
// Loop through each array element, get JSON object which has Title and Des
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("Id"));
System.out.println(obj.get("Title_Audio"));
System.out.println(obj.get("URL_Audio"));
// DB QueryValues Object to insert into SQLite
queryValues = new HashMap<String, String>();
// Add ID extracted from Object
queryValues.put("id", obj.get("Id").toString());
// Add Title extracted from Object
queryValues.put("title", obj.get("Title_Audio").toString());
// Add Des extracted from Object
queryValues.put("url", obj.get("URL_Audio").toString());
// Insert User into SQLite DB
dbHandler.insertWriteAudio(queryValues);
HashMap<String, String> map = new HashMap<String, String>();
// Add status for each User in Hashmap
map.put("id", obj.get("Id").toString());
map.put("title", obj.get("Title_Audio").toString());
map.put("url", obj.get("URL_Audio").toString());
usersynclist.add(map);
}
// Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users
//updateMySQLSyncSts(gson.toJson(usersynclist));
// Reload the Main Activity
reloadActivity();
Toast.makeText(getApplicationContext(), "Sync activity completed successfully.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My DBhandler Code:
public void truncateTable(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ MP_TABLE);
}
public void insertWriteAudio(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", queryValues.get("Id"));
values.put("title", queryValues.get("title"));
values.put("url", queryValues.get("url"));
database.insert("audios", null, values);
database.close();
}
public int getMpAudioRowCount() {
SQLiteDatabase db = this.getReadableDatabase();
long cnt = DatabaseUtils.queryNumEntries(db, MP_TABLE_Audio);
db.close();
return (int) cnt;
}
You can download only the updated content from database server. This is how you can do that. It will need some changes in your schema -
On Server side
Add one more column in the database, 'Updated_On' which will contain
the timestamp when that record was updated on the server
When you are inserting or updating any new record in the databse,
change the 'Updated_On' field accordingly
Now make some changes on the client side
On Client Side
In your Android app, keep a note of what was the last change that
was downloaded, i.e. the last download was made for 'Updated_On' =
{some past time stamp} (You can do that in SharedPreferences on cancreate a SQLite table)
When you query to download, query for all records who have
'Updated_On' > {some past time stamp}
If the record exist in your local SQLite database, update it; else insert the record in your SQLite databse
To help you get started, where you are making the AsyncHttp call
....
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
params.put("latestChange",lastUpdateTimestamp);
//where lastUpdateTimestamp is the sharedPreference value you are keeping of last update
client.get(getApplicationContext().getString(R.string.IpAdd) + "/WebApi/api/mpAudioapi/GetAllAudio", params, new AsyncHttpResponseHandler() {
....
On your server side you get that post variable $lastUpdate = $_POST['latestChange']. Now use the variable $lastUpdate in your API to query the database Select * from table where Updated_On > $lastUpdate
I'm new in Multiplayer programming. How to set String into hashmap value ? I want to call hashmap properties from RoomListActivity and set it's value on QuizMaintain activity and also I want to set hashmap value from QuizMaintain class to textview. Here's my sample code
RoomListActivity
public void onJoinNewRoomClicked(View view){
progressDialog = ProgressDialog.show(this,"","Please wait...");
progressDialog.setCancelable(true);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("timer", "");
properties.put("question", "");
properties.put("answer", "");
properties.put("foulanswer", "");
theClient.createRoom(""+System.currentTimeMillis(), "Yoshua", 2, properties);
}
Then I want to set it's value from QuizMaintain activity
public class QuizMaintain extends Activity implements RoomRequestListener, NotifyListener {
private WarpClient theClient;
private HashMap<String, Object> properties;
private TextView txttimer,txtquestion;
private String roomId = "";
private HashMap<String, User> userMap = new HashMap<String, User>();
String string="5x5#5x4#150:3#500:20#536+59";
String[] questions = string.split("#");
String question1 = questions[0];
String question2 = questions[1];
String question3 = questions[2];
String question4 = questions[3];
String question5 = questions[4];
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_maintain);
txttimer = (TextView)findViewById(R.id.timer);
txtquestion = (TextView)findViewById(R.id.questionview);
try{
theClient = WarpClient.getInstance();
}catch(Exception e){
e.printStackTrace();
}
theClient.getLiveRoomInfo("143680827");
Intent intent = getIntent();
roomId = intent.getStringExtra("roomId");
init(roomId);
//setquestionview();
}
private void init(String roomId){
if(theClient!=null){
theClient.addRoomRequestListener(this);
theClient.addNotificationListener(this);
theClient.joinRoom(roomId);
}
}
#Override
public void onGetLiveRoomInfoDone(LiveRoomInfoEvent event) {
properties = event.getProperties();
properties.put("question", question1);
}
I want to set hashmap value where is the key are "question". And the value that i want to set are from split string.When I ask their support team if I want to get room properties I should call getLiveRoomInfo method and pass roomID as argument. A bit confused here. Thanks.
But it seems my problem are not solved yet. After call method updateRoomProperties but I got another error here. It's say WarpClient.AddZoneRequestListener(this) return null pointer exception
When you are creating a room you are passing a hashmap. This hashmap is stored as a JSON document inside the room on server. AppWarp calls it Room Properties.
Now to retrieve these properties you have to call getLiveRoomInfo method. This will present you the room properties. Here you are adding/changing some key-value again. But you haven't told the server that you are updating these room properties. Therefore your changes remain local and that too limited to the scope of function.
So, when you call the getLiveRoomInfo method, you won't see the changes as you haven't updated them on server. To update on server, you need to call updateRoomProperties method. In this method you can add or change your hashmap.
I have a fairly simple question, how would I name a variable using another variable.
For example:
public static void addSortListItem(int group_id) {
if (lists.contains(group_id)) {
// add item to correct array list
} else {
lists.add(group_id);
// create new array list using the group_id value as name identifier
ArrayList<ExpListObject> group_id = new ArrayList<ExpListObject>();
}
}
In this function I need to create a new arrayList using the group_id integer as the name. The error here is obviously a duplicate local variable, but what is the correct way to name this?
Any help is appreciated!
You are using group_id as both an identifier name and parameter name. That doesn't make sense. Instead, map the new ArrayList to the group_id. For example:
HashMap<Integer,ArrayList<ExpListObject>> hm = new HashMap<Integer,ArrayList<ExpListObject>>();
hm.put(group_id, new ArrayList<ExpListObject>());
You can make something like this using HashMap, this way:
public static void addSortListItem(int group_id) {
//Create a HashMap to storage your lists
HashMap<String, ArrayList<ExpListObject>> mapList = new HashMap<String, ArrayList<ExpListObject>>();
ArrayList<Object> array = mapList.get(String.valueOf(group_id));
if (array != null) {
array.add(new ExpListObject());
} else {
// Insert the new Array into the HashMap
mapList.put(String.valueOf(group_id), new ArrayList<ExpListObject>());
}
}
Or this way:
public static void addSortListItem(int group_id) {
//Create a HashMap to storage your lists
HashMap< Integer, ArrayList<ExpListObject>> mapList = new HashMap< Integer, ArrayList<ExpListObject>>();
ArrayList<Object> array = mapList.get(group_id);
if (array != null) {
array.add(new ExpListObject());
} else {
// Insert the new Array into the HashMap
mapList.put(group_id, new ArrayList<ExpListObject>());
}
}