how to extract jsonarray in java when two arrays in output - android

How to retrieve the ids array from the following JSON Object.
{"bets":[{"bet":[{"gid":"10","Result":null}]},{"bet":[{"gid":"7","Result":null}]},{"bet":[{"gid":"3","Result":null},{"gid":"6","Result":"2"}]},{"bet":[{"gid":"6","Result":"2"},{"gid":"4","Result":"1"}]},{"bet":[{"gid":"6","Result":"2"},{"gid":"4","Result":"1"}]}]}{"ids":["9c9nogs6of","ank4kt3gqo","jfgrt91nk4","a8qmoq7v4q","8mov5ita1t"]}
I've tried
allids = jObj.getJSONArray("ids");
which should work because it works with jObj.getJSONArray("bets"); however I receive this error in logcat E/Buffer Error﹕ Error converting result org.json.JSONException: No value for ids
PHP FILE
<?php
// get tag
$param= $_POST['param'];
$bet = explode("//",$param);
$allbetslength = count($bet);
$ultresponse["bets"] = array();
$idresponse["ids"] = array();
for ($x = 0; $x < $allbetslength; $x++) {
$indid = substr($bet[$x],0,10);
array_push($idresponse["ids"], $indid);
$bet[$x] = substr($bet[$x],10);
$id = explode(",",$bet[$x]);
$arrlength = count($id);
// include db handler
require_once 'include/Check_Bets.php';
$db = new Check_Bets();
$response["bet"] = array();
for($y = 0; $y < $arrlength; $y++) {
$result= $db->checkuserbets($id[$y]);
array_push($response["bet"], $result);
}
array_push($ultresponse["bets"], $response);
array_push($ultresponse["bets"], $idresponse["ids"]);
}
echo json_encode($ultresponse);
?>

Related

Image upload in an Oracle database using Zend Framework

I am uploading an image from my android application and trying to store the image as Blob in Oracle database using PHP. I used the same technique for uploading the image in my web application which worked fine. I am trying the following code. Need some assistance. TIA
<?php
$conn = oci_connect("test_dev","test_dev","192.168.10.82:1509/testdv");
class emp{}
$image = $_POST['image'];
$name = $_POST['name'];
if (empty($name)) {
$response = new emp();
$response->success = 0;
$response->message = "Please dont empty Name.";
die(json_encode($response));
} else {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $image);
$DIGI_TYPE= $mime;
$lob = oci_new_descriptor($conn, OCI_D_LOB);
$myv = file_get_contents($image);
$imageProperties = getimageSize($image);
$lob->writeTemporary($myv, OCI_TEMP_BLOB);
$sql = "UPDATE LC_BLOCK_LIST_TECH_PERS
SET DIGI_SIGN = :DIGI_SIGN , DIGI_TYPE = :DIGI_TYPE
WHERE COM_CODE= '$name'";
$s = oci_parse($conn, $sql);
oci_bind_by_name($s, ':DIGI_TYPE', $DIGI_TYPE);
oci_bind_by_name($s, ':DIGI_SIGN', $lob, -1, OCI_B_BLOB);
oci_execute($s, OCI_NO_AUTO_COMMIT);
oci_commit($conn);
$lob->close();
`
<?php
$conn = oci_connect("DRUG_FINAL","DRUG_FINAL","192.168.10.85:1521/devdb");
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
else{
echo "connected";
}
$image = $_POST['image'];
$name = $_POST['name'];
if(isset($_POST["image"]) && isset($_POST["name"]))
{
$title = $_POST["name"];
$image = $_POST["image"];
$gambar = file_get_contents($image);
$gambar1 =file_put_contents(base64_decode($gambar1));
$query = "INSERT INTO images (TITLE, IMAGES) VALUES (:TITLE, EMPTY_BLOB()) RETURNING IMAGES INTO :IMAGES";
$parse = oci_parse($conn, $query);
$lob_a = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($parse, ":TITLE", $title);
oci_bind_by_name($parse, ":IMAGES", $lob_a, -1, OCI_B_BLOB);
oci_execute($parse, OCI_DEFAULT);
if($lob_a->save($gambar1))
{
oci_commit($conn);
$lob_a->free();
}
else
{
oci_rollback($conn);
}
}

json utf-8 encoding for android

i have some persian(utf8) words on my database for my android app and i am using json for show database information in android app.
I have following code on Databasemanager.php:
function getMusics()
{
$connection = mysqli_connect(DatabaseManager::HOST_NAME, DatabaseManager::USER_NAME, DatabaseManager::PASSWORD, DatabaseManager::DATABASE_NAME);
$sqlQuery = "SELECT * FROM musics where active = 1 order by date desc;";
$result = $connection->query($sqlQuery);
$musicsArray = array();
if ($result->num_rows > 0) {
for ($i = 0; $i < $result->num_rows; $i++) {
$musicsArray[$i] = $result->fetch_assoc();
}
}
echo json_encode($musicsArray);
}
and in GetMusic.php for get json information :
<?php
include "DatabaseManager.php";
$databaseManager = new DatabaseManager();
$databaseManager->getMusics();
but i have bellow jsons on output :
{"id":"3","name":"???","artist":"????? ????","like_count":"1","comment_count":"0","dl_link":null,"photo":"http:\/\/192.168.88.6\/musicarea\/photos\/3.jpg","active":"1","date":"2017-08-04 00:00:00"}
how can i solve it ??
on output(i just use persian language at 2 last rows):
on the app:
on php my admin:
You should set the default client charset to UTF-8. Use mysqli::set_charset OR mysqli_set_charset.
See http://de2.php.net/manual/en/mysqli.set-charset.php for more info.
You have to add the header that it tells the client the response is encoding with utf-8
header('Content-Type: text/html; charset=utf-8');
EDIT
function getMusics()
{
$connection = mysqli_connect(DatabaseManager::HOST_NAME, DatabaseManager::USER_NAME, DatabaseManager::PASSWORD, DatabaseManager::DATABASE_NAME);
$sqlQuery = "SELECT * FROM musics where active = 1 order by date desc;";
$result = $connection->query($sqlQuery);
$musicsArray = array();
if ($result->num_rows > 0) {
for ($i = 0; $i < $result->num_rows; $i++) {
$musicsArray[$i] = $result->fetch_assoc();
}
}
header("Content-type: application/json; charset=utf-8");
echo json_encode($musicsArray);
}

Session token right usage with API

Can anyone please explain -
I am writing a Php code that will allow a mobile app (Android) to get data from the DB.
I read about using a token but where do I save this token on the server side?
(I tried it, but the session token variable doesn't exist I assign it - for example, if I call it the second time.)
<?php
session_start();
$sql = "SELECT * FROM a_users WHERE a_mail = '".$_POST["mail"]."' AND a_pw = '".$_POST["pw"]."'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
$value = $result->fetch_assoc();
$Token_API = encryptMyVar(date('Y-m-d H:i:s'));
$_SESSION["Token_API"] = $API_Token;
$value = array("login" => 1,"token_api" => $Token_API,"nickname" => $value["nickname"]);
$con->close();
exit(json_encode($value));
}
?>
should i save the token in a file on the server or something or am I doing something wrong?
Thank you!!!
So after looking at your code, it isn't a big problem. All you have is the variable your are setting the Session to is $API_Token, that variable doesn't exist. You should mean to set $_SESSION["Token_API"] to $Token_API. Your final code should look something like this:
<?php
session_start();
$sql = "SELECT * FROM a_users WHERE a_mail = '".$_POST["mail"]."' AND a_pw = '".$_POST["pw"]."'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
$value = $result->fetch_assoc();
$Token_API = encryptMyVar(date('Y-m-d H:i:s'));
$_SESSION["Token_API"] = $Token_API; //Replaced $API_Token with $Token_API
$value = array("login" => 1,"token_api" => $Token_API,"nickname" => $value["nickname"]);
$con->close();
exit(json_encode($value));
}
?>
Please do tell me if this solves your problem ;).

Titanium Alloy Android Login

I am having an issue with a Titanium App, the issue is only with Android, iOS is fine.
So I have a login form that queries the database, pretty straightforward. But for some reason it is not passing the params to the login script.
My JS function in app, have set the alert on the else statement to print out the $.email.value and password values which read fine. But with the current $response which is just a json it shows the values as being blank? The php form is also below. As I have said this is working fine on iOS
function login(e) {
//function to use HTTP to connect to a web server and transfer the data.
var sendit = Ti.Network.createHTTPClient({
onerror : function(e) {
Ti.API.debug(e.error);
alert('There was an error during the connection');
},
timeout : 100000,
});
//Here you have to change it for your local ip
sendit.open('GET', 'http://soyo.taylorhoganit.co.uk/post_auth.php');
var params = {
email : $.email.value,
password : $.password.value,
};
sendit.send(params);
//Function to be called upon a successful response
sendit.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true)
{
var landing = Alloy.createController("landing").getView();
$.index.close();
landing.open();
// Ti.App.Properties.setString('email', $.email.value);
// Ti.App.Properties.setString('password', $.password.value);
//alert("Username: " + response.username);
}
else
{
alert($response);
}
};
};
PHP Script
<?php
// Connect to the database(host, username, password)
$con = mysql_connect('replaced values');
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db('soyo');
if (!$db)
{
echo "Failed to select db.";
exit;
}
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email = '" . $email . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$response = array(
'logged' => true,
'email' => $row['email']
);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
'logged' => false,
'message' => $email + $password
);
echo json_encode($response);
}
?>
You did a mistake by using $response in the alert. It is a PHP variable not JS.
var response = JSON.parse(json);
// ...
alert($response); // Here should be just `response`
Edit: The another problem is that you are sending GET request while in PHP you accept POST ,so you can't get any params...
There is a mistake when you want to show alert.
You are using now is alert($response);
Remove $ from $response and use alert(response);, it will work properly.

Connection reset when downloading to Android from Rails

I have an android application I am trying to sync with a rails app.
In the android app I download and load a json object from the server (using an OAuth token for authentication):
private JSONArray getJSON(URL url, String authToken) throws IOException, JSONException {
URLConnection con = url.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + authToken);
InputStream is = new BufferedInputStream(con.getInputStream());
Scanner s = new Scanner(is).useDelimiter("\\A");
String text = s.hasNext() ? s.next() : "";
return new JSONArray(text);
}
I'm trying to reload the existing data and it is ~380k. When I run the code I get the following in the rails server log:
Started GET "/events.json?created_since=0" for 192.168.1.111 at 2014-01-22 20:15:16 -0500
Processing by EventsController#index as JSON
Parameters: {"created_since"=>"0", "event"=>{}}
Doorkeeper::AccessToken Load (0.6ms) SELECT "oauth_access_tokens".* FROM "oauth_access_tokens" WHERE "oauth_access_tokens"."token" = [:filtered:] ORDER BY "oauth_access_tokens"."id" ASC LIMIT 1
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 501661262]]
Habit Load (0.7ms) SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ? ORDER BY "habits"."id" ASC LIMIT 1000 [["user_id", 501661262]]
Event Load (26.7ms) SELECT "events".* FROM "events" WHERE "events"."habit_id" = ? [["habit_id", 1]]
⋮
Rendered events/index.json.jbuilder (3422.5ms)
Completed 200 OK in 4491ms (Views: 3436.2ms | ActiveRecord: 73.4ms)
[2014-01-22 20:15:21] ERROR Errno::ECONNRESET: Connection reset by peer
/home/will/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:80:in `eof?'
/home/will/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:80:in `run'
/home/will/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
The connection reset is repeated seven times. The client receives about 260k of data. app/views/events/index.json.jbuilder is:
json.array!(#events) do |event|
json.extract! event, :id, :habit_id, :time, :description
end
The same method is used to load a different model with only a few entries and it loads correctly. Is there a limit to how big a file can be downloaded? In any case pagination seems like a good idea. Anyone know of any guidelines on what size chunks I ought to break it up into?
Instead using Scanner, maybe you can use Reader to read the result InputStream
Reader reader = new InputStreamReader(is);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(reader).getAsJsonArray();
I ended up paginating the data and it now loads correctly:
JSONArray events;
int page = 1;
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
batch = new ArrayList<ContentProviderOperation>();
do {
events = getJSON(new URL(EVENT_READ_URL + "?page=" + (page++)), authToken);
for(int i = 0; i < events.length(); i++) {
JSONObject event = events.getJSONObject(i);
batch.add(ContentProviderOperation.newInsert(HabitContentProvider.EVENTS_URI)
.withValue(EventTable.COLUMN_ID, event.getInt("id"))
.withValue(EventTable.COLUMN_HABIT_ID, event.getInt(EventTable.COLUMN_HABIT_ID))
.withValue(EventTable.COLUMN_TIME, timeFormat.parse(event.getString(EventTable.COLUMN_TIME)).getTime() / 1000)
.withValue(EventTable.COLUMN_DESCRIPTION, event.getString(EventTable.COLUMN_DESCRIPTION))
.build());
}
} while(events.length() > 0);
try {
mContentResolver.applyBatch(HabitContentProvider.AUTHORITY, batch);
} catch(SQLiteConstraintException e) {
Log.e(TAG, "SQLiteConstraintException: " + e.getMessage());
}
In my rails code I added the will_paginate gem, included array support, and added the following to my code:
if params[:page]
#events = #events.paginate(page: params[:page], per_page: params[:per_page] || 300)
end

Categories

Resources