Android Capacitor JS Plugin does not reply - javascript

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.

Related

Generate HMAC SHA Algorithm using URI and Key

I wrote a Java program which generates HMAC SHA hash code, But due to some reason I have to write the same code in NodeJs/JavaScript. I tried googling around but did not get anything. In this Java code, I am passing URI and Key as arguments, to generate the hash code, where URI contains Timestamp.
The java code is as :
public static String calcMAC(String data, byte[] key) throws Exception {
String result=null;
SecretKeySpec signKey = new SecretKeySpec(key, SecurityConstants.HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(SecurityConstants.HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac;
try {
rawHmac = mac.doFinal(data.getBytes("US-ASCII"));
result = Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
public static void main(String args[]) {
String timestamp = args[0];
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC("/req?app_id=47ca34" + timestamp + "=2018-05-22T12:02:15Z",
key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to achieve the same goal in NodeJs/JavaScript?
Note:: I have to call this script from Postman pre-request script.
The crypto module should do this for you, you can substitute the 'data' variable with whatever you want to hash:
const crypto = require('crypto');
const data = 'The fault dear Brutus lies not in our stars';
const key = Buffer.from('d134hjeefcgkahvg32ajkdbaff84ff180', 'utf8');
const hash = crypto.createHmac('sha1', key).update(data).digest('base64');
const uriEncodedHash = encodeURIComponent(hash);
console.log('Hash: ' + uriEncodedHash);
Hashing the data in both Java and Node.js gives me the result (URI Encoded) of:
TJJ3xj93m8bfVpGoucluMQqkB0o%3D
The same Java code would be:
public static void main(String args[]) {
String data = "The fault dear Brutus lies not in our stars";
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC(data, key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Again, we can put anything into 'data' we want.

j2v8 Object from nodejs script not accesible

I try to run a nodeJS script with j2v8 in my Java project and it runs normally but i can't get the Array or any other JScript Objects although this functionality is offered through j2v8. Additionally the script uses a npm module called Blocktrail which generates the Array. The call for the Object is in the function testExportAnalyzer(). Here it throws that the Object does not contain "test". Please, can anyone explain how i can use the variables or the needed Array in my Java Code or what I do wrong?
public ScriptLoader(String adr) {
address = adr;
addressInformation = null;
NODE_SCRIPT = ""
+"var test = \"123456\";\n"
+"var blocktrail = require('/blocktrail-sdk');\n"
+"var addressInformation = null;\n"
+"var client = blocktrail.BlocktrailSDK({apiKey : \"xxxxxx\", apiSecret : \"xxxxxx\"});\n"
+"client.address(\""+address+"\", function(err, address) {\n"
+" if (err) {\n"
+" console.log('address ERR', err);\n"
+" return;\n"
+" }\n"
+" addressInformation = address;"
+"console.log('address:', address['address'], 'balance:', address['balance'] / blocktrail.COIN, 'sent and received in BTC:', address['sent'] / blocktrail.COIN, address['received'] / blocktrail.COIN, 'number of transactions:', address['total_transactions_out'], address['total_transactions_in']);\n"
+"});\n"
+"\n"
+"client.addressTransactions(\""+address+"\", {limit: 100}, function(err, address_txs) {\n"
+" console.log('address_transactions', address_txs['data'].length, address_txs['data'][0]);\n"
+"});";
}
public void executeAnalyzerScript() throws IOException {
final NodeJS nodeJS = NodeJS.createNodeJS();
JavaCallback callback = new JavaCallback() {
public Object invoke(V8Object receiver, V8Array parameters) {
return "Hello, JavaWorld!";
}
};
nodeJS.getRuntime().registerJavaMethod(callback, "someJavaMethod");
File nodeScript = createTemporaryScriptFile(NODE_SCRIPT, "addressScript");
nodeJS.exec(nodeScript);
while(nodeJS.isRunning()) {
nodeJS.handleMessage();
}
nodeJS.release();
}
public void testExportAnalyzer() throws IOException {
NodeJS nodeJS = null;
File testScript = createTemporaryScriptFile(NODE_SCRIPT, "Test");
nodeJS = NodeJS.createNodeJS();
V8Object exports = nodeJS.require(testScript);
while(nodeJS.isRunning()) {
nodeJS.handleMessage();
}
System.out.println(exports.contains("test"));
exports.release();
}
private static File createTemporaryScriptFile(final String script, final String name) throws IOException {
File tempFile = File.createTempFile(name, ".js.tmp");
PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
try {
writer.print(script);
} finally {
writer.close();
}
return tempFile;
}
public void setAddress(String input) {
address = input;
}
I had some success by writing variables like this in the Javascript code:
global.myvar = "myval";

How to display and interact with OKHTTP html response in android Studio using webview or Web browser

I am building an android app. I have build a request using OKHTTP and I get the response as a string composed of html css and js content. This response is actualy a form that the user must use to allow the app to communicate with a given website.
Now I want the user to be able to see that response as an html page and clicks on a button to allow the communictaion. Only problem I don't know how to display that response as an html in webview or in the web browser.
From the MainActivity:
Authenticate myAouth = new Authenticate("myCostumerKey","mySecretKey");
try {
myResponse=myAouth.run("myUrlHere");
//System.out.println( myResponse);
} catch (Exception e) {
e.printStackTrace();
}
the Autheticate class
public class Authenticate {
private final OkHttpClient client;
String[] myResponse =new String[2];
public Authenticate( final String consumerKey, final String consumerSecret) {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
if (response.request().header("Authorization") != null) {
return null; // Give up, we've already attempted to authenticate.
}
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic(consumerKey, consumerSecret);
Request myRequest =response.request().newBuilder()
.header("Authorization", credential)
.build();
HttpUrl myURL = myRequest.url();
myResponse[0]= String.valueOf(myURL);
return myRequest;
}
})
.build();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String[] run(String url) throws Exception {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
myResponse[1]=response.body().string();
System.out.println(" URL is "+myResponse[0]+" my response body is "+myResponse[1]);
}
return myResponse;
}}
Any help would be apriciated.
Kind Regards
You can use the following code to convert the String to HTML and then display it in a WebView
try {
String html = new String(response, "UTF-8");
String mime = "text/html";
String encoding = "utf-8";
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

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