Disable Javascript on volley StringRequest - javascript

I have a volley StringRequest in my MainActivity like this
StringRequest strReq = new StringRequest(Method.POST,
G.serverLevelAdress, new Listener<String>() {
#Override
public void onResponse(String response) {
// TODO Auto-generated method stub
Log.e(TAG, "Response to get All Online Users \n "
+ response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (error.getMessage() != null)
Log.e(TAG, TAG + ": " + error.getMessage());
try {
G.showToast(activity.getResources().getString(
R.string.network_error));
} catch (Exception e) {
// TODO: handle exception
}
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "getAllOnlineUsers");
params.put("email", email);
return params;
}
};
G.getInstance().addToRequestQueue(strReq, tag_string_req);
In local host, everything works fine and I would easily call a local server. This is my php code to request and returns its response :
<?php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "error" => FALSE);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["user_unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
$response["user"]["paycard"] = $user["paycard"];
$response["user"]["phone"] = $user["phone"];
$response["user"]["real_name"] = $user["real_name"];
$response["user"]["role"] = $user["role"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missinggg!";
echo json_encode($response);
}
?>
The problem is when the code I loaded on the online host I receive this message as an response :
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
Where is the problem? How can I disable Javascript through activity I send my request?
Infinitely thank you for your attention.

Related

Android Capacitor JS Plugin does not reply

I am working on a java plugin that is supposed to recieve some info from a js vue3 program and then do a URL post operation, and then return some of the info found back to the js code. I am using capacitor and android. This is my error message:
2022-08-22 13:46:23.773 27544-27544/org.theguy.GptEtc E/Capacitor/Console: File: http://localhost/js/app.6577adf2.js - Line 1 - Msg: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
I think this means that something other than valid JSON is being delivered to the js code. I know that the app is delivering info to the java android class. This is some of my java code.
#CapacitorPlugin(name = "URLPOST")
public class PluginURLPost extends Plugin {
#PluginMethod()
public void post(PluginCall call) {
String post_url = call.getString("post_url", "");
String bearer = call.getString("bearer", "pipeline_");
JSObject ret = new JSObject();
try {
String value = this.doPost(post_url, bearer);
System.out.println("value " + value);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(value));
ResultPreview preview = gson.fromJson(reader, ResultPreview.class);
String val = preview.getResult_preview()[0][0];
val = "result string here."; // <-- add this for easy testing
ret.put("response_text", val.replace("\n", "\\n"));
System.out.println("response here: " + val);
}
catch (Exception e) {
e.printStackTrace();
}
//call.setKeepAlive(true);
call.resolve(ret);
}
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
String doPost(String post_url, String bearer ) throws IOException {
// ... do some post request here ...
return response_body;
}
}
class ResultPreview {
#SerializedName("result_preview")
String [][] result_preview ;
public void setResult_preview(String[][] result) {
this.result_preview = result;
}
public String[][] getResult_preview() {
return this.result_preview;
}
}
This is some of my js code.
import { registerPlugin } from "#capacitor/core";
const URLPOST = registerPlugin("URLPOST");
const request = {
"line": line,
"pipeline_model": details[engine]["app_model"].trim(),
"bearer": details[engine]["api_key"].trim(),
"post_url": details[engine]["url"].trim(),
"length": 25,
"top_k": 50
};
console.log("request", request);
var {response_text} = await URLPOST.post(request);
console.log("response_text 1",response_text);
I don't know what to do.
I tried this, and things work better. I don't know if this is the ultimate solution.
#PluginMethod()
public void post(PluginCall call) {
bridge.saveCall(call); // <-- add this
call.release(bridge); // <-- add this
String pipeline_model = call.getString("pipeline_model", "pipeline_");
String post_url = call.getString("post_url", "");
JSObject ret = new JSObject();
try {
String value = this.doPost(post_url);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(value));
ResultPreview preview = gson.fromJson(reader, ResultPreview.class);
String val = preview.getResult_preview()[0][0];
ret.put("response_text", val.replace("\n", "\\n"));
System.out.println("response here: " + val);
}
catch (Exception e) {
e.printStackTrace();
}
call.resolve(ret);
}
This is not found on the capacitor site, but instead I found it digging around the internet.

How to protect AJAX or javascript web application

This is a simple function that use AJAX and get information about an image in the database with id=219 when a button is clicked
Anyone loading this webpage can change the javascript code by going to the source code.
Then by clicking the button he will run the modified code (like changing image_id from 219 to 300). So he can get information about any image just by changing image_id
The question is how to protect against that client-side attack or XSS ?
function clicked () {
var xhttp = new XMLHttpRequest () ;
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200){
var obj = JSON.parse (this.responseText);
alert (obj.description);
}
};
xhttp.open ("POST","get_title_description.php", true);
xhttp.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
xhttp.send ("image_id=219") ;
}
You can use something like this for generating and validating the cookie:
define('COOKIE_TOKEN', 'my_token');
class BaseAuth
{
protected $uid;
private static function base64url_encode(string $s): string
{
return strtr($s,'+/=','-|_');
}
private static function base64url_decode(string $s): string
{
return strtr($s,'-|_','+/=');
}
// Encodes after encryption to ensure encrypted characters are URL-safe
protected function token_encode(String $string): string
{
$iv_size = openssl_cipher_iv_length(TYPE_CRYPT);
$iv = openssl_random_pseudo_bytes($iv_size);
$encrypted_string = #openssl_encrypt($string, TYPE_CRYPT, SALT, 0, $iv);
// Return initialization vector + encrypted string
// We'll need the $iv when decoding.
return self::base64url_encode($encrypted_string).'!'.self::base64url_encode(base64_encode($iv));
}
// Decodes from URL-safe before decryption
protected function token_decode(String $string): string
{
// Extract the initialization vector from the encrypted string.
list($encrypted_string, $iv) = explode('!', $string);
$string = #openssl_decrypt(self::base64url_decode($encrypted_string), TYPE_CRYPT, SALT, 0, base64_decode(self::base64url_decode($iv)));
return $string;
}
// performs log-out
public function clear_cookie()
{
setcookie(COOKIE_TOKEN, '', time() - 300, '/api', '', FALSE, TRUE); // non-secure; HTTP-only
}
private function userIP(): string
{
return $_SERVER['REMOTE_ADDR'];
}
// validates Login token
public function authorized(): bool
{
if(isset($_COOKIE[COOKIE_TOKEN]))
{
$stamp = time();
$text = $this->token_decode($_COOKIE[COOKIE_TOKEN]);
if($text != '')
{
$json = json_decode($text,TRUE);
if(json_last_error() == JSON_ERROR_NONE)
{
if($json['at'] <= $stamp AND $json['exp'] > $stamp AND $json['ip'] == $this->userIP() AND $json['id'] != 0)
{
// check if user account is still active
$res = $db->query("SELECT id,active,last_update,last_update > '".$json['last']."'::timestamptz AS expired FROM account WHERE id = ".$json['id']);
$info = $db->fetch_assoc($res);
if($info['active'] != 0)
{
if($info['expired'] == 0)
{
// extend the token lifetime
$this->sendToken($info);
$this->uid = $json['id'];
return TRUE;
}
}
}
}
}
$this->clear_cookie();
}
return FALSE;
}
public function login(String $username, String $password): bool
{
$stm = $db-prepare("SELECT id,user_name AS username,user_pass,full_name,active,last_update,COALESCE(blocked_until,NOW()) > NOW() AS blocked
FROM account WHERE user_name = :user");
$res = $stm->execute(array('user' => strtolower($json['username'])));
if($res->rowCount())
{
$info = $db->fetch_assoc($res);
if($info['active'] == 0)
{
// Account is disabled
return FALSE;
}
elseif($info['blocked'] != 0)
{
// Blocked for 5 minutes - too many wrong passwords
// extend the blocking
$db->query("UPDATE account SET blocked_until = NOW() + INTERVAL 5 minute WHERE id = ".$info['id']);
return FALSE;
}
elseif(!password_verify($password, $info['user_pass']))
{
// Wrong password OR username
// block account
$db->query("UPDATE account SET blocked_until = NOW() + INTERVAL 5 minute WHERE id = ".$info['id']);
return FALSE;
}
else
{
unset($info['user_pass']);
unset($info['blocked']);
$this->sendToken($info);
return TRUE;
}
}
}
}
If you do not need to authenticate and authorize your users and just need random unpredictable image IDs - you can simply use UUIDs.

How to get parametr in response from spring? (rest Javascript)

I have a problem with returning an error to html. So, I have web-app with "sql interpreter".
HTML
<button type="submit" onclick="executeSQL('interpreterSQL')">
<i class="fas fa-bolt"></i>
</button>
<textarea id="interpreterSQL" placeholder="❔❔❔"></textarea>
After entering a query into the interpreter, I run POST in javascript and shoot to spring:
POST in JavaScript
function executeSQL(interpreterSQL) {
var tmp = document.getElementById(interpreterSQL).value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("POST", "/user/executeSQL", true);
xhttp.send(tmp);
}
After that I handle the query in my service and return message to POST in my Controller:
Controller (POST in Spring)
#PostMapping(path = { "/user/executeSQL" })
public ModelAndView executeSQL(#RequestBody String tmp) {
String[] split = tmp.replace("\n", "").replace("\t", "").split(";");
String feedback = databaseTableService.executeSQL(split);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("successMessage", feedback);
modelAndView.setViewName("/user/interpreterSQL");
return modelAndView;
}
Service which is used to execute native query
public String executeSQL(String[] split){
SessionFactory hibernateFactory = someService.getHibernateFactory();
Session session = hibernateFactory.openSession();
String message = null;
for (int i = 0; i < split.length; i++) {
try{
String query = split[i];
session.doWork(connection -> connection.prepareStatement(query).execute());
message = "Success";
}
catch(Exception e){
message = ((SQLGrammarException) e).getSQLException().getMessage();
}
}
session.close();
return message;
}
So finally we are in my controller which is ready to return value and we have message which is have information about sql exceptions. We are there:
And here is my question: How to get variable "feedback" in response?
I need to handle that value there i think:
but that "var response = xhttp.responseText" is returning all my HTML code. I need only parametr "feedback" from my controller.
Guys can someone help? :( I don't know how to send that parametr in return and handle it in javascript...
Maybe you can change your Controler method to return JSON response instead on ModelAndView
#PostMapping(path = { "/user/executeSQL" })
public ResponseEntity<Object> executeSQL(#RequestBody String tmp) {
String[] split = tmp.replace("\n", "").replace("\t", "").split(";");
Map<String,String> response = new HashMap<String, String>();
response.put("feedback", databaseTableService.executeSQL(split));
return new ResponseEntity<>( response , HttpStatus.OK);
}
Now you should be able to see the status
var response = xhttp.responseText;
console.log("ok"+response);

Tableau Integration with Web project

I am doing Tableau integration with web project using java script api. I have configured my ip in tableau server using commnad :tabadmin set wgserver.trusted_hosts "" and respective commands .But I am not able to get the ticket, ended up with -1. I have followed all configuration steps.
public class TableauServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public TableauServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String user = "raghu";
final String wgserver = "103.xxx.xxx.xx";
final String dst = "views/Regional/College?:iid=1";
final String params = ":embed=yes&:toolbar=yes";
String ticket = getTrustedTicket(wgserver, user, request.getRemoteAddr());
if ( !ticket.equals("-1") ) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "http://" + wgserver + "/trusted/" + ticket + "/" + dst + "?" + params);
}
else
// handle error
throw new ServletException("Invalid ticket " + ticket);
}
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
private String getTrustedTicket(String wgserver, String user, String remoteAddr)
throws ServletException
{
OutputStreamWriter out = null;
BufferedReader in = null;
try {
// Encode the parameters
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(user, "UTF-8"));
data.append("&");
data.append(URLEncoder.encode("client_ip", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(remoteAddr, "UTF-8"));
// Send the request
URL url = new URL("http://" + wgserver + "/trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception e) {
throw new ServletException(e);
}
finally {
try {
if (in != null) in.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
}
}
I think you are missing 'target_site' parameter in your URL where you get trusted ticket, its needed if you don't have the 'views/Regional/College' in your default site.
I had gone through a lot of frustration with the '-1' ticket too!
One thing you might try is restarting the tableau server after you have added your web server IP to the trusted_hosts of tableau.
Another thing we ended up doing was adding both the internal ip and external ip of the web server to trusted_hosts on tableau. Since you are using 103.xxx.xxx.xx as your tableau server I am assuming both servers live on the same internal network. You might try that if everything else fails.
My code is almost exactly same as yours and works fine. So if your problem persists, it must be something related to configuration.
here is my code:
private String getAuthenticationTicket(String tableauServerUserName,String tableauServerUrl, String targetSite) {
OutputStreamWriter out = null;
BufferedReader in = null;
try {
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(tableauServerUserName, Constant.UTF_8));
data.append("&");
data.append(URLEncoder.encode("target_site", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(targetSite, Constant.UTF_8));
URL url = new URL(tableauServerUrl + "/" + "trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception ex) {
//log stuff, handle error
return null;
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ex) {
//log stuff, handle error
}
}
}

Adding new line to database and unexpectedly closes app

I am currently a beginner to android programming and right now I am developing an app to make a JSON connection to a LAMP server and display the JSON data. The connection is currently successfully being made and i can create product and see it in the db but the app unexpectedly close's every time, can someone help and point me in the right direction, will add more if needed.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
is = null;
jObj = null;
json = "";
// Making HTTP request
try {
Log.i("url", url);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.i("url", url);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.i("url", url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("Stage 1", "Stage 1");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("1 ", line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("Stage 2", "Stage 2");
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.i("Stage 3", "Stage 3");
// return JSON String
return jObj;
}
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.1.165/wp-admin/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
#SuppressWarnings("ResourceType")
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
logcat 09-16 10:47:27.285
23440-23458/com.example.androidhive.productjsonphp I/OpenGLRenderer﹕
Initialized EGL, version 1.4 09-16 10:47:27.287
23440-23458/com.example.androidhive.productjsonphp D/OpenGLRenderer﹕
Enabling debug mode 0 09-16 10:47:28.372
23440-23440/com.example.androidhive.productjsonphp V/Monotype﹕
SetAppTypeFace- try to flip, app =
com.example.androidhive.productjsonphp 09-16 10:47:28.372
23440-23440/com.example.androidhive.productjsonphp V/Monotype﹕
Typeface getFontPathFlipFont - systemFont = default#default 09-16
10:47:28.449 23440-23471/com.example.androidhive.productjsonphp
I/url﹕
http://api.androidhive.info/android_connect/get_all_products.php 09-16
10:47:28.451 23440-23471/com.example.androidhive.productjsonphp
I/url﹕
http://api.androidhive.info/android_connect/get_all_products.php?
09-16 10:47:28.674 23440-23458/com.example.androidhive.productjsonphp
D/OpenGLRenderer﹕ endAllStagingAnimators on 0xb7f62f50
(RippleDrawable) with handle 0xb7f75e00 09-16 10:47:29.017
23440-23471/com.example.androidhive.productjsonphp I/Stage 1﹕ Stage 1
09-16 10:47:29.022 23440-23471/com.example.androidhive.productjsonphp
I/1﹕ Unknown database 'download_androidhive' 09-16 10:47:29.022
23440-23471/com.example.androidhive.productjsonphp I/Stage 2﹕ Stage 2
09-16 10:47:29.023 23440-23471/com.example.androidhive.productjsonphp
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value
Unknown of type java.lang.String cannot be converted to JSONObject
09-16 10:47:29.023 23440-23471/com.example.androidhive.productjsonphp
I/Stage 3﹕ Stage 3 09-16 10:47:29.029
23440-23471/com.example.androidhive.productjsonphp E/AndroidRuntime﹕
FATAL EXCEPTION: AsyncTask #1
Process: com.example.androidhive.productjsonphp, PID: 23440
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a
null object reference
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818) 09-16 10:47:29.528 23440-23440/com.example.androidhive.productjsonphp
E/WindowManager﹕ android.view.WindowLeaked: Activity
com.example.androidhive.productjsonphp.AllProductsActivity has leaked
window com.android.internal.policy.impl.PhoneWindow$DecorView{78d7c4f
V.E..... R......D 0,0-479,116} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.androidhive.productjsonphp.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.androidhive.productjsonphp.AllProductsActivity.onCreate(AllProductsActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5255)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:838)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651) 09-16
10:47:34.521 23440-23471/com.example.androidhive.productjsonphp
I/Process﹕ Sending signal. PID: 23440 SIG: 9
Your try to parse Json from String "json" but this "json" string give null value, if Please check "json" string is null, before use it.
so, try this code
if(json!=null && !json.equals(""))
{
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
)else{
Toast.makeText(context, "json is empty", Toast.LENGTH_LONG).show();
}

Categories

Resources