Android WebView error Failed to init browser shader disk cache - android-webview

My code opens a index.html file in a webView but failed to open the css and js files, the errors I am getting are:
E/SysUtils: ApplicationContext is null in ApplicationStatus
E/chromium: [ERROR:browser_gpu_channel_host_factory.cc(258)] Failed to init browser shader disk cache.
E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
all the files referenced to in the <head> of the index.html are located in the assets folder as siblings of index.html
package au.com.totalcareauto.webappandroid1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
WebView wv = (WebView) findViewById(R.id.wv);
wv.setWebViewClient(new WebViewClient());
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
String summary = null;
String path = "file:///assets/";
try {
summary = getStringFromFile("index.html");
} catch (Exception e) {
e.printStackTrace();
}
wv.loadDataWithBaseURL(path ,summary,"text/html","utf-8",null);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public String getStringFromFile(String filePath) throws Exception {
File fl = new File(filePath);
String ret = convertStreamToString(this.getAssets().open(filePath));
return ret;
}
}
<head>
<meta charset="UTF-8">
<title>RRR</title>
<link type="text/css" rel="stylesheet" href="jquery.mobile-1.4.5.css"/>
<link type="text/css" rel="stylesheet" href="index.css"/>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script type="text/javascript" src="jquery.mobile-1.4.5.js"></script>
<meta name="viewport" content="width=device-width"/>
</head>

The log does not reflect the cause the loading failure.
The issue is you have wrong path:
String path = "file:///assets/";
Which should be:
String path = "file:///android_asset/";

Related

How to change the default folder for uploading file in jboss

I am trying to upload a file, I am trying to change the default location of the uploaded file. How to change this please suggest ?
package Controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import requests.Connect;
import display.DisplayLog;
/** * Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
boolean result;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 1000 * 1024;
private int maxMemSize = 1000 * 1024;
private File file ;
public ControlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession();
String userName = request.getParameter("username");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("audio/mpeg3;audio/x-mpeg-3;video/mpeg;video/x-mpeg;text/xml");
PrintWriter out = response.getWriter( );
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
String root = getServletContext().getRealPath("/");
root = "F/images";
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(" Prashant File Upload Location is ");
// System.out.println(uploadedFile.getAbsolutePath());
System.out.println("fileName is " +fileName);
System.out.println("root is " + root);
System.out.println("path is " + path);
if(fileName!="")
{
item.write(uploadedFile);
System.out.println(" Prashant File Upload Location 2 is ");
System.out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
System.out.println("file not found");
}
}
else
{
String abc = item.getString();
}
}
} catch (FileUploadException e) {
out.println(e);
} catch (Exception e) {
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
System.out.println("print this Prashant" + userName);
session.setAttribute("username",userName);
request.setAttribute("username","prashant");
// RequestDispatcher myDispatch = request.getRequestDispatcher("Index.jsp");
//myDispatch.forward(request, response);
}
}
I am getting this as default folder F:\jboss-4.2.3.GA-jdk6\jboss-4.2.3.GA\bin\ please help i am new to this
Your problem is here:
String root = getServletContext().getRealPath("/");
you are setting the upload path to the containers path, not a default path but the place where the server started from. You can make the upload path anything you want it to be, it depends on your needs and configuration.
You could create a system property with the directory of your choice, you could set it as a dynamic property in a JBoss configuration file (not sure what that would be for JBoss4).

How do I know a file is uploading in a Fileupload?

UploadEvent only sent to Fileupload component when the file is uploaded, but I would like to be noticed when the file start to upload. Is there anyway for doing this ?
Example:-
index.zul
<?page title="Auto Generated index.zul"?>
<window title="Drop here" border="normal" width="100%" height="100%"
apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('com.demo.DropFileViewModel')">
<dropupload maxsize="5120" detection="none"
onUpload="#command('doUpload')">
</dropupload>
<button label="Download" onClick="#command('doDownload')"></button>
</window>
DropFileViewModel.java
package com.demo;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.util.media.Media;
import org.zkoss.zhtml.Filedownload;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Messagebox;
public class DropFileViewModel {
Media media;
#Command
public void doUpload(#ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) {
UploadEvent upEvent = null;
Object objUploadEvent = ctx.getTriggerEvent();
if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
upEvent = (UploadEvent) objUploadEvent;
}
if (upEvent != null) {
media = upEvent.getMedia();
Messagebox.show("File Uploaded: " + media.getName());
}
}
#Command
public void doDownload() {
if (media != null)
Filedownload.save(media);
else
Messagebox.show("First Drop Your File");
}
}

Only one of the two AutoCompleteTextView are showing suggestions

I have two AutoCompleteTextView controls on the same page: ACTV1 and ACTV2 and only one (ACTV1 ) is showing suggestions from my database . For each databinding action I've made a java class separetely: ACTV1.java and ACTV2.java.
But if I am adding an intent filter (MAIN, LAUNCHER) in my manifest file for ACTV2.java class and setting in run configuration ACTV2.java as Launch Action then I won't get suggestions anymore for ACTV1 control but this time I'll get suggestions for ACTV2 control.
The two java classes are identically just that differ the name of some constants/controls name.
package com.fishing2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class CompleteBalti extends Activity {
//private CustomAutoCompleteView CompleteBalti;
private ArrayAdapter<String> adaperbalti;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partida);
}
final TextWatcher textChecker = new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count)
{
adaperbalti.clear();
callPHP1();
}
};
private void callPHP1(){
String result = "";
InputStream is=null;
AutoCompleteTextView CompleteBalti = (AutoCompleteTextView) findViewById(R.id.nume_localitate);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("st",CompleteBalti.getText().toString()));
{
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.3.159/wtf/balti.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
result = result.substring(1);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i=0;i<jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
adaperbalti.add(json_data.getString("nume_balta"));
}
} catch(Exception e1){
Log.e("log_tag", "Error converting result "+e1.toString());
}
}
}
}

Cannot instantiate the type Iterator in JSP (Exception: The value for the useBean class attribute ... is invalid)

this is my code, it seems right to me! i don't know why it keeps saying this:
"Cannot instantiate the type Iterator"
this is the servlet:
package uges.servlets;
import jess.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Iterator;
public class Catalog extends BaseServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
checkInitialized();
try {
String customerId =
(String) request.getParameter("customerId");
if (customerId == null || customerId.length() == 0) {
dispatch(request, response, "/index.html");
return;
}
request.getSession().invalidate();
HttpSession session = request.getSession();
session.setAttribute("customerId", customerId);
session.setAttribute("orderNumber",
String.valueOf(getNewOrderNumber()));
ServletContext servletContext = getServletContext();
Rete engine = (Rete) servletContext.getAttribute("engine");
Iterator result =
engine.runQuery("all-products", new ValueVector());
request.setAttribute("queryResult", result);
} catch (JessException je) {
throw new ServletException(je);
}
dispatch(request, response, "/catalog.jsp");
}
this is the dispatch method, it 's in a servlet called BaseServlet:
protected void dispatch(HttpServletRequest request,
HttpServletResponse response,
String page)
throws IOException, ServletException {
ServletContext servletContext = getServletContext();
RequestDispatcher dispatcher =
servletContext.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
and this the JSP code:
<HTML>
<%# page import="jess.*" %>
<jsp:useBean id="queryResult" class="java.util.Iterator" scope="request"/>
the error is about the java.util.Iterator in the class type of useBean tag!
the exception says : The value for the useBean class attribute java.util.Iterator is invalid
any help please ..
Thanks in advance!
java.util.Iterator is an Interface, not a Class. You want
<jsp:useBean id="queryResult" type="java.util.Iterator" scope="request"/>
To confirm this I used the following test code:
package org.apache.markt.so;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Q001Servlet")
public class Q001Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
request.setAttribute("list", list.iterator());
RequestDispatcher rd = request.getRequestDispatcher("/so/q001.jsp");
rd.forward(request, response);
}
}
With the following /so/q001.jsp
<html>
<jsp:useBean id="list" type="java.util.Iterator" scope="request" />
<body>
<p><%=list.next()%></p>
</body>
</html>
This was using HEAD from the latest development branch but you'll see the same results with the latest Tomcat 7 release.
Here is a JSP that demonstrates my idea.
<%# page import="java.util.*" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
//for testing
List<String> engineList = new ArrayList<String>();
engineList.add("zero");
engineList.add("one");
engineList.add("two");
engineList.add("three");
Iterator<String> result = engineList.iterator();
// create a list from engine result
List<String> list = new ArrayList<String>();
while(result.hasNext())list.add(result.next());
request.setAttribute("list", list);
%>
<html>
<body>
Complete list is${list}
The first item is ${list[0]}.
The second item is ${list[1]}.
If you don't know how many items there are in result, then use JSTL
<c:forEach var="item" items="${list}" >
${item}
</c:forEach>
</body>
</html>

capturing the image using android camera [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling camera from an activity, capturing an image and uploading to a server
i am very new to android, i am trying to capture the image after that i placed that image into image view,its working on emulator but in device it crashes it shows the message force close even it cannot open the camera activity.the following is my code.
please help me how to solve this problem.thank you.
package com.gss.android;
package com.gss.android;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Pictures extends Activity{
Button btnsave,btnnewpic;
protected ImageView image;
protected String _path;
File sdImageMainDirectory;
private static final int IMAGE_CAPTURE = 0;
protected boolean _taken = true;
private Uri imageUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAMERA_PIC_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pictures);
btnsave=(Button)findViewById(R.id.btnsave);
btnnewpic=(Button)findViewById(R.id.btnnewpic);
btnnewpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCameraActivity2();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode == CAMERA_PIC_REQUEST){
if (resultCode == RESULT_OK){
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
Log.e("file path", "stiring file") ;
} catch (Exception e) {
e.printStackTrace();
}
finish();
}
}
} else if ( requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Log.d("ANDRO_CAMERA","Picture taken!!!");
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageURI(imageUri);
}
}
}
protected void startCameraActivity2()
{
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testphoto.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(Pictures.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(Pictures.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
Log.e("file dir",imageDir.toString());
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think this is a problem related to the emulator and not the physical device.
I used this code and I got a bitmap:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
imageView = (ImageView)findViewById(R.id.image);
destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
//Bitmap userImage = (Bitmap)data.getExtras().get("data");
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10; //Downsample 10x
Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
imageView.setImageBitmap(userImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Add extra to save full-image somewhere
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
Toast.makeText(JMABarcodeScannerActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(intent, REQUEST_IMAGE);
}
};
}
Main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"
/>
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerInside"
/>
</LinearLayout>