I've got a database which I use in my android app (accounts).
I want the user to be able to change his/her password.
I'm using java, mySQL, PHP and JSON.
The username needs to be updated by their id, I just created the code to do this but I get an error...: "Error parsing data org.json.JSONException: Value < br>< table of type java.lang.String cannot be converted to JSONObject".
Here are some lines of code, I use:
PHP
$query = "UPDATE users SET username = :username WHERE id = :id";
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
I also need to check if the username is succesfully updated, but I'll do that later.
I just use:
$response["success"] = 1;
$response["message"] = "Username is succesfully changed!";
die(json_encode($response));
JAVA
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
id = sp.getInt("id", 1);
EditText newUsername = (EditText)findViewById(R.id.etNewUsername);
username = newUsername.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Integer.toString(id)));
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
Log.d("After updating username", json.toString());
But the Tag: "After updating username" doesn't appear after the error in the LogCat.
So I know the error is within the HttpRequest.
Maybe it's the id? Because it will be converted to a String and in the database the id is an integer?
Every help will be appreciated!
Thanks.
Error parsing data org.json.JSONException: Value < br>< table of type java.lang.String cannot be converted to JSONObject
Notice the value- "<br> <table". You're trying to treat HTML as JSON. That doesn't work, so the JSONParser is throwing an exception. You don't catch the exception, so you crash.
Related
i am trying get list of intermediate railway stations information from https://rbs.indianrail.gov.in/ShortPath/ShortPath.jsp, by providing source and destination stations it displays list of intermediate stations within a table. but its hiding some intermediate stations under several buttons to limit the size of the table,i think. on clicking the buttons, it pushes hidden data on to the table. using jsoup i could get initial data in the table. but dont know how to get the hidden data. on button click, one javascript function requesting data using POST method from https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet by passing "route=inter,index=1,distance=goods,PageName=ShortPath" as parameters and the response is in json. as the parameters are not relevant to the displayed table, i can not make direct request to the https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet.
private void shortestPath(String source, String destination) {
Document doc;
try {
doc = Jsoup.connect(url)
.data("srcCode", source.toUpperCase())
.data("destCode", destination.toUpperCase())
.data("guageType", "S")
.data("transhipmentFlag", "false")
.data("distance", "goods")
.post();
Element table = doc.select("tbody").get(0);
Elements rows = table.select("tr");
stationCodeList = new String[rows.size() - 3];
jsonPath = new JSONObject();
for (int row = 3; row < rows.size(); row++) {
JSONObject jsonObject = new JSONObject();
Elements cols = rows.get(row).select("td");
String code = cols.get(1).text();
String name = cols.get(2).text();
String cum_dist = cols.get(3).text();
String inter_dist = cols.get(4).text();
String gauge = cols.get(5).text();
String carry_cap = cols.get(6).text();
jsonObject.put("Code", code);
jsonObject.put("Name", name);
jsonObject.put("Cumulative Distance", cum_dist);
jsonObject.put("inter Distance", inter_dist);
jsonObject.put("Gauge Type", gauge);
jsonObject.put("Carrying Capacity", carry_cap);
jsonPath.put(code, jsonObject);
stationCodeList[row - 3] = code;
}
} catch (Exception e) {
e.printStackTrace();
}
this.destination =new Station(stationCodeList[stationCodeList.length-1]);
}
thank you in advance
If you take a look at this answer, you'll see how to get the exact same request the browser has made.
The minimal and valid POST request to the StationXmlServlet, using your example, would look something like this with curl:
curl --request POST 'https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Cookie: JSESSIONID1=0000ob7e89cT3vUAYkBxF6oyW4w:APP2SERV1' \
--data-raw 'route=inter&index=1&distance=goods&PageName=ShortPath'
As the parameters are not relevant to the displayed table, i can not make direct request to the https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet.
I don't think that's true. The index in the body of the request is the zero-based index of rows in the master table.
Solution
It turns out that you simply have to follow the exact same order as you do when you use the page in a web browser. In other words, you have to first load the master table so that the site knows which table you are viewing when you want to query for details. A session cookie keeps track of this state.
First, you open the landing page and get a Cookie:
HttpRequest cookieRequest = HttpRequest.newBuilder()
.uri(URI.create("https://rbs.indianrail.gov.in/ShortPath/ShortPath.jsp"))
.GET()
.build();
HttpResponse<String> cookieResponse =
client.send(cookieRequest, BodyHandlers.ofString());
String cookie = cookieResponse.headers().firstValue("Set-Cookie").get();
Next, you load the master table, given the specified form parameters:
HttpRequest masterRequest = HttpRequest.newBuilder()
.uri(URI.create("https://rbs.indianrail.gov.in/ShortPath/ShortPathServlet"))
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Cookie", cookie)
.POST(BodyPublishers.ofString("srcCode=RGDA&destCode=JSWT&findPath0.x=42&findPath0.y=13&gaugeType=S&distance=goods&PageName=ShortPath"))
.build();
HttpResponse<String> masterResponse =
client.send(masterRequest, BodyHandlers.ofString());
String masterTableHTML = masterResponse.body();
// Document masterTablePage = Jsoup.parse(masterTableHTML);
// ...
Finally, you can query the details for each row of the master table. In the example bellow, we query the details of the first row.
HttpRequest detailsRequest = HttpRequest.newBuilder()
.uri(URI.create("https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet"))
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Cookie", cookie)
.POST(BodyPublishers.ofString("route=inter&index=0&distance=goods&PageName=ShortPath"))
.build();
HttpResponse<String> detailsResponse =
client.send(detailsRequest, BodyHandlers.ofString());
String jsonResponse = detailsResponse.body();
System.out.println(jsonResponse);
I need to receive all entries from a MySQLi database with a certain value (in my case: The Facebook-ID).
First im sending the value which im searching for in the database (fb_id):
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fb_id", fb_id));
JSONObject json = jParser.makeHttpRequest(url_your_events, "GET", params);
Receiving it in PHP:
if (isset($_GET['fb_id'])) {
$fb_id = $_GET['fb_id'];
Then having the query:
$result = mysqli_query($con, "SELECT * FROM UserEvents WHERE fb_id == $fb_id");
I already used different types for the fb_id column. BigInt (the ID would not fit in normal int) and VarChar do not work - i'm not getting any results.
How do i get the query to work properly?
I'm grateful for any advice!
EDIT:
I also tried different comparisons in the query: = / == / === but none worked.
I would like to append a Bloomberg API response to a MySQL database using Java.
At the moment I query the API and display the response using the below code:
session.sendRequest(request, null);
while (true) {
Event event = session.nextEvent();
MessageIterator msgIter = event.messageIterator();
while (msgIter.hasNext()) {
Message msg = msgIter.next();
new JSONObject(msg);
System.out.println(msg);
}
if (event.eventType() == Event.EventType.RESPONSE) {
break;
}
}
I would like to be able to append the msg object to a table in a MySQL database. The msg object looks like it is a JSON format (although I am unsure how to confirm this).
I also have no problems connecting to the MySQL table using JDBC.
Step 5 connected with select query, in you case at step 4 you need use update query and no step 5 will be required. You need to get fields values from json and put them in update statement. To get values from json:
//example json string
String json = "{paramsArray: [\"first\", 100],"
+ "paramsObj: {one: \"two\", three: \"four\"},"
+ "paramsStr: \"some string\"}";
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;
System.out.println(jsonObj.get("paramsStr"));
JsonObject jo = jsonObj.get("paramsObj");
System.out.println(jo.get("three"));
// output will be 'four'
Here reference to update query in mysql: https://dev.mysql.com/doc/refman/5.0/en/update.html
With Rally's rest api, how can I query to find a user's email address?
For instance, I have this query to get a defect which contains the full name of the user who opened it and the user who owns the defect:
QueryRequest defectRequest = new QueryRequest("defect");
defectRequest.setFetch(new Fetch("Project", "LastUpdateDate", "FormattedId"));
defectRequest.setQueryFilter(new QueryFilter("Project.Name", "=", rallyProjectName).and(new QueryFilter("LastUpdateDate", ">", defectTimestamp.getTimestamp())));
QueryResponse projectDefects = rallyApi.query(defectRequest);
Now I'd like to take the Submitted By and Owner users from the defect and get their email addresses.
Make certain to include the fields "Owner" and "SubmittedBy" on your Fetch for the Defects:
defectRequest.setFetch(new Fetch("Project", "LastUpdateDate", "FormattedId", "Owner", "SubmittedBy"));
Then the Owner and SubmittedBy fields on each returned Defect (if populated in Rally and not null) will have a reference to the corresponding User object in Rally. Then your inclination to do a second request for this is spot on. It's easiest to just use that ref and do a GetRequest straight against the ref. Here's how on the Owner field as an example (forgive the clumsy try/catch block - it's catching empty Owner fields):
QueryResponse projectDefects = restApi.query(defectRequest);
if (projectDefects.wasSuccessful()) {
for (JsonElement result : projectDefects.getResults()) {
JsonObject defect = result.getAsJsonObject();
try {
JsonObject ownerJsonObject = defect.get("Owner").getAsJsonObject();
String ownerRef = ownerJsonObject.get("_ref").getAsString();
GetRequest ownerRequest = new GetRequest(ownerRef);
GetResponse ownerResponse = restApi.get(ownerRequest);
JsonObject ownerObj = ownerResponse.getObject();
System.out.println(String.format("Read owner. EmailAddress = %s",
ownerObj.get("EmailAddress").getAsString()));
} catch (java.lang.IllegalStateException ise) {
// System.out.println("IllegalStateException caught: ");
// ise.printStackTrace();
}
}
}
I tried to retrieve multiple rows of JSON data and display it but im not able to retrieve all the rows,im only getting the top(first) row of the database table.And im confused about how can i put the retrieved JSON data into some sort of array and access the individual rows?
I have provided the code relevant to the problem.
Yes i have done enough research before posting this question.I actually found one question which was some what similar to mine but nobody has answered it so i'm making this post.
Thank You
Below is the code from my Freebies.java class where i'm trying to retrieve JSONdata by calling getAllFreebies function from UserFunctions.java class
UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();
System.out.println(json);
Below is the code of the function getAllFreebies() in the class UserFunctions.java
public JSONObject getAllFreebies(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
JSONObject json = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
return json;
}
Below is the code from index.php where im calling getFreebies() function from DB_Function.php file
else if($tag = 'getAllFreebies'){
$getAllFreebies = $db->getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
if($getAllFreebies)
{
$response["success"] = 1;
$response["getAllFreebies"]["username"] = $getAllFreebies["username"];
$response["getAllFreebies"]["catagory"] = $getAllFreebies["catagory"];
$response["getAllFreebies"]["subcatagory"] = $getAllFreebies["subcatagory"];
$response["getAllFreebies"]["title"] = $getAllFreebies["title"];
$response["getAllFreebies"]["item_condition"] = $getAllFreebies["item_condition"];
$response["getAllFreebies"]["description"] = $getAllFreebies["description"];
$response["getAllFreebies"]["address"] = $getAllFreebies["address"];
$response["getAllFreebies"]["city"] = $getAllFreebies["city"];
$response["getAllFreebies"]["state"] = $getAllFreebies["state"];
$response["getAllFreebies"]["country"] = $getAllFreebies["country"];
$response["getAllFreebies"]["zipcode"] = $getAllFreebies["zipcode"];
$response["getAllFreebies"]["posted_on"] = $getAllFreebies["posted_on"];
echo json_encode($response);
}else {
$response["error"] =1;
$response["error_msg"] = "Error in getAllFreebies";
echo json_encode($response);
}
}// end of getAllFreebies tag
Below is the code of my getFreebies() function of DB_function.php which is responsible for performing queries on MySQL database.
public function getFreebies(){
$result = mysql_query("SELECT * FROM freebie") or die(mysql_error());
return mysql_fetch_array($result);
}
Below is the logcat:
05-30 00:13:23.960: E/JSON(318): {"tag":"getAllFreebies","success":1,"error":0,"getAllFreebies":{"username":"viking","catagory":"Art","subcatagory":"Potrait","title":"Potrait","item_condition":"Good","description":"potarit","address":"Blah St","city":"lalaland","state":"NA","country":"NA","zipcode":"blah","posted_on":"2012-05-27"}}
mysql_fetch_array() only returns a single row of the query result set as an array. It does not fetch ALL of the rows. Since you're returning the results of the fetch from your getFreebies method, instead of the result handle itself, it is impossible for the calling code to get any other results from the query, other than the one row you've fetched.
As such, you should have:
public function getFreebies() {
$result = ...
return($result);
}
and
$getAllFreebies = $db->getFreebies(...);
$data = array();
while($row = mysql_fetch_assoc($getAllFreebies)) {
$data[] = array(
.... your variable assignments here ...
);
}
echo json_encod($data);