Adding new line to database and unexpectedly closes app - javascript

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();
}

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.

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
}
}
}

How to send data to server javascript using get request

I'm new to Java and Android development and try to create a simple app which should contact a web server A and send,add some data to text using a http get.
I have simple HTML code with some javascript (server A)
<html>
<head>
<title>This is my Webpage</title>`enter code here`
<h1>My Example</h1>
<script>
function myFunction(){
document.getElementById("myid").value=$ab;
}
</script
</head>
<body onload="myFunction()">
<input id="myid" type="text" />
</body>
</html>
and i have Android code to send http request to a local (server A)
public class MainActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.localhost/tuan/example.html";
MyCommandTask task = new MyCommandTask();
task.execute(url);
}
});
}
public class MyCommandTask extends AsyncTask<String,Void,Document>
{
#Override
protected Document doInBackground(String... params) {
String url=params[0];
try {
HttpGet httpGet = new HttpGet(url);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
}
}
}``
Now i want send text data and show result in text on (server A).
Please anyone help me.
Check this out dude. http://developer.android.com/training/basics/network-ops/connecting.html#download . Since you already got url string in doInBackground() method , use below code
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
Don't forget to change return type of doInBackground() to String as well. If you wanna go further , try grab volley which is one of the awesome network library https://developer.android.com/training/volley/index.html
Here is how you can post data to server. Put these line inside doInBackground()
private static final String POST_PARAMS = "userName=Pankaj";
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
Here is the source

loading an image file hosted in assets folder exposed with web server in the app

In my app, I have created web server which is hosting a web app. All the files of web app are placed in assets folder.
Now, i start the web server by running my application and then from crome brower, I try to run my web app by calling index.html file. The html, css part of the page is getting loaded properly but the images are not getting loaded in the page:
Here is my HttpRequestHandlerCode:
public class HomePageHandler implements HttpRequestHandler {
private Context context = null;
private static final Map<String, String> mimeTypes = new HashMap<String, String>() {
{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xhtml", "text/xhtml");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("svg", "image/svg+xml");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
put("m3u8", "application/vnd.apple.mpegurl");
put("ts", " video/mp2t");
}
};
public HomePageHandler(Context context){
this.context = context;
}
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
//String contentType = "text/html";
//Log.i("Sushill", "..request : " + request.getRequestLine().getUri().toString());
final String requestUri = request.getRequestLine().getUri().toString();
final String contentType = contentType(requestUri);
String resp = Utility.openHTMLStringFromAssets(context, "html" + requestUri);
writer.write(resp);
writer.flush();
// }
}
});
((EntityTemplate) entity).setContentType(contentType);
response.setEntity(entity);
}
}
/**
* Get content type
*
* #param fileName
* The file
* #return Content type
*/
private String contentType(String fileName) {
String ext = "";
int idx = fileName.lastIndexOf(".");
if (idx >= 0) {
ext = fileName.substring(idx + 1);
}
if (mimeTypes.containsKey(ext)) {
//Log.i("Sushill", "...ext : " + ext);
return mimeTypes.get(ext);
}
else
return "application/octet-stream";
}
To handle image, I tried this but it did not work :
if(contentType.contains("image")) {
InputStream is = Utility.openImageFromAssets(context, "html" + requestUri);
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can someone please help me in figuring out how to load the images also in my browser.
Thanks for any help
Do away with BufferedReader(new InputStreamReader' so you do away with UTF-8 too. Use only InputStream 'is'. Do away with writer. You are not showing what 'writer' is but do away with it. Use the OutputStream of the http connection. Keep the buffer and the loop where you read in the buffer and write from the buffer.

Get content string (not source code) of webPage on Android

I made a Javascript page to generate a JSON object for read it then from Android device.
I read it with the following code
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null){
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to donwload file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is that this code returns the source code of the webpage, and the source code is the script in Javascript, not the JSON string generated after execute it.
I need the JSON string and I need use Javascript to generate the JSON string because I access to an external service.
I haven't find any solution for this. I don't care if the possible solution involves the server or the Android terminal.
Thanks.
String myresponse=Html.escapeHtml(YourStringHere);
Try this.
private class MyJavaScriptInterface {
private MyJavaScriptInterface () {
}
public void setHtml(String contentHtml) {
//here you get the content html
}
}
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.ResponseChecker.setHtml"
+ "(document.body.innerHTML);");
}
}

Categories

Resources