When I run this code repeated - except the first time, null pointer exception is thrown even though the file already exists.
static public class writeexcel {
public void write(){
try{
File f = new File("C:/Users/acer/Desktop/2.xls");
Workbook existingbook=null;
WritableWorkbook ww;
WritableSheet sr;
if(!f.exists()){
ww = Workbook.createWorkbook(f);
sr = ww.createSheet("mysheet", 0);
}else{
existingbook = Workbook.getWorkbook(f);
ww = Workbook.createWorkbook(f, existingbook);
sr = ww.getSheet("Mysheet");
}
Label lb = new Label(0, 0, " success");
Label lb1 = new Label (1,5,"new task");
sr.addCell(lb);
sr.addCell(lb1);
ww.write();
ww.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
writeexcel exl = new writeexcel() ;
exl.write();
}
}
Try beloe code, it will write "Success"in 100 cells and rows. you can then modify it as per your requirement.
public class Test {
public static void main(final String[] args) {
Test exl = new Test();
exl.write();
}
public void write() {
try {
File f = new File("fileLocation.xls");
Workbook existingbook = null;
WritableWorkbook ww;
WritableSheet sr;
if (!f.exists()) {
ww = Workbook.createWorkbook(f);
sr = ww.createSheet("mysheet", 0);
} else {
existingbook = Workbook.getWorkbook(f);
ww = Workbook.createWorkbook(f, existingbook);
sr = ww.getSheet("Mysheet");
}
for (int i = 0; i < 100; i++) {
for (int x = 0; x < 100; x++) {
Label lb1 = new Label(i + 1, x + 1, "new task");
// Label lb = new Label(i, x, " success");
// sr.addCell(lb);
sr.addCell(lb1);
}
}
ww.write();
ww.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I've got a problem with my web-scraper. It should execute a javascript to make some changes on a webpage, then download the source and extract some specific data.
bool working = true;
for(int i = 0; i < urls.Count(); ++i)
{
working = true;
ChromiumWebBrowser scraper = new ChromiumWebBrowser(urls[i]);
scraper.FrameLoadEnd += scrape;
while(working)
{
Application.DoEvents();
System.Threading.Thread.Sleep(50);
}
}
async void scrape(object sender, FrameLoadEndEventArgs args)
{
ChromiumWebBrowser chrome = (ChromiumWebBrowser)sender;
if (args.Frame.IsMain && chrome.CanExecuteJavascriptInMainFrame)
{
string script = Properties.Resources.script;
chrome.ExecuteScriptAsync(script);
string data = " ";
do
{
string html = await chrome.GetSourceAsync();
string dataField = "data";
int dataFieldIndex = html.IndexOf(phoneField);
data = html.Substring(dataFieldIndex + dataField.Count(), html.IndexOf("<", dataFieldIndex + dataField.Count()) - dataFieldIndex - dataField.Count());
System.Threading.Thread.Sleep(50);
} while (data.Count() == 3);
addDataToHashSet(data);
}
else
{
Debug.WriteLine("Error");
}
}
private void addDataToHashSet(string data)
{
data = data.Replace("-", "");
data = data.Replace(" ", "");
dataHashSet.Add(data);
working = false;
}
Unfortunately, it's unpredictable. It hangs after few iterations - a proper event with CanExecuteJavascriptInMainFrame and IsMain is never triggered for some iterations. Could you explain it to me?
[edit]: My Cef initialization below:
CefSettings cefSettings = new CefSettings();
cefSettings.CefCommandLineArgs.Add("allow-running-insecure-content", "1");
cefSettings.IgnoreCertificateErrors = true;
CefSharpSettings.Proxy = new ProxyOptions(ip: "...", port: "...");
Cef.Initialize(cefSettings);
I'm trying to update my map so that the map automatically moves to centre the marker. I want it such that if I move around, after 5 seconds, the map will animate itself to move such that the marker is central again.
Here is the code:
public class TrackDifferentLocation extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LatLng mLatlng;
String json_string;
public static TextView data;
LatLng latLng = null;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Toast.makeText(this, "Tracking location...", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_track_different_location);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//new FetchJSON.execute(); //Not valid syntax
new FetchJSON().execute();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.i("", "onMapReady()");
displayMarkers();
}
private void displayMarkers(){
if (mMap == null)return;
//If mLatlng is null (as the Async task has not finished, then nothing will happen.
if(mLatlng == null) return;
//The camera and map will then update to the new location with zoom.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatlng, 17));
mMap.addMarker(new MarkerOptions().position(mLatlng).title(String.valueOf(mLatlng)));
}
//Part of menu see following
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
//ends the activity
this.finish();
}
switch (item.getItemId()) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
class FetchJSON extends AsyncTask<String, Integer, LatLng> {
String JSONStr = "";
String name, address, type = "";
String lat = "";
String lng = "";
String id = "";
//double lat, lng;
int idInt;
double latDouble = -1;
double lngDouble = -1;
protected LatLng doInBackground(String... args) {
//LatLng latLng = null;
try {
//URL url = new URL("https://api.myjson.com/bins/ehzqu");
URL url = new URL("https://api.myjson.com/bins/sv5vm");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d("BufferedReader: ", String.valueOf(bufferedReader));
String line = "lind";
while (line != null) {
line = bufferedReader.readLine();
JSONStr = JSONStr + line;
}
Log.d("", JSONStr);
JSONObject obj = new JSONObject(JSONStr);
JSONArray array = obj.getJSONArray("server response");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
id = o.optString("id");
name = o.optString("name");
address = o.optString("address");
lat = o.optString("lat");
lng = o.optString("lng");
Log.d("lat: ",lat);
latDouble = Double.parseDouble(lat);
lngDouble = Double.parseDouble(lng);
latLng = new LatLng(latDouble, lngDouble);
Log.i("JSON Values", lat + " " + lng);
type = o.optString("type");
}
} catch (Exception ex) {
Log.e(TAG, "FetchJSON --- " + ex.getMessage());
}
return latLng;
}
protected void onPostExecute(LatLng latLng) {
if (latLng != null) {
mLatlng = latLng;
displayMarkers();
}
}
}
}
Please note, for the question I have removed all imports and package.
To demonstrate how this can work I have changed the code which is more applicable to your code:
int index = 0;
private void loadLocation() {
new FetchJSON().execute();
startAutoHandler();
}
class FetchJSON extends AsyncTask<String, Integer, LatLng> {
#Override
protected LatLng doInBackground(String... params) {
LatLng latLng = null;
try {
URL url = new URL("https://api.myjson.com/bins/sv5vm");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String json = stringBuilder.toString();
Log.e(TAG, "Return = " + json);
String lat= "";
String lng= "";
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("server response");
for(int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
lat = o.optString("lat");
lng = o.optString("lng");
}
Log.e(TAG, "Lat = " + lat);
Log.e(TAG, "lng = " + lng);
index++;
double adjustLat = 0.1 * index;
double adjustLng = 0.01 * index;
double latDouble = Double.parseDouble(lat) + adjustLat;
double lngDouble = Double.parseDouble(lng) + adjustLng;
latLng = new LatLng(latDouble, lngDouble);
}
catch (Exception ex) {
Log.e(TAG, "doInBackground --- " + ex.getMessage());
}
return latLng;
}
#Override
protected void onPostExecute(LatLng latLng) {
try{
if(latLng != null){
mLatLng = latLng;
displayMarker();
}
}
catch(Exception ex){
Log.e(TAG, "onPostExecute" + ex.getMessage());
}
}
}
private void displayMarker(){
if(mMap == null) return;
if(mLatLng == null) return;
mMap.clear();
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(mLatLng);
CameraUpdate loc = CameraUpdateFactory.newLatLngZoom(mLatLng, 10.3f);
mMap.animateCamera(loc);
mMap.addMarker(markerOption);
}
Handler mAutoHandler = new Handler();
long delay = 2000l; //this delay is in ms change as needed
private void startAutoHandler(){
try{
Log.e(TAG, "startAutoHandler");
mAutoHandler.postDelayed(mAutoRunnable, delay);
}
catch (Exception ex){
Log.e(TAG, ex.getMessage());
}
}
private Runnable mAutoRunnable = new Runnable() {
#Override
public void run() {
new FetchJSON().execute();
mAutoHandler.postDelayed(mAutoRunnable, delay);
}
};
private void stopAutoHandler(){
mAutoHandler.removeCallbacks(mAutoRunnable);
}
You will need to call stopAutoHandler(); in your onPause() method. Otherwise it will carry on and can cause some real issues!
*This is a school project
I'v been using this project on couple of computers, in the first computer my project run perfectly, but on other computer it's giving me a System.AccessViolationException on 'random' places on code.
I'm using web service, asmx page and aspx pages, my database is Microsoft Access.
I'm trying to belive the bug is a problem with my second computer settings and not on my code, because the code run perfect on others computer.
This is one place that giving me a bug:
javascript:
function sendList(r, id, subject, content) {
$('#modal1').modal('close');
$.getJSON("/API/UIService.asmx/SendMessage?currentUserID=" + id + "&reciverID=" + r + "&subject=" + subject + "&content=" + content, function (msg) {
msg = fixMsg(msg);
if (msg == "Message sent") {
modalAlert(fixMsg(msg));
inbox.update();
sent.update();
}
else
alert(msg);
});
}
Web service method:
[WebMethod]
public void SendMessage(int currentUserId, string reciverID, string subject, string content)
{
try
{
string[] res = reciverID.Split(',');
List<Message> m = new List<Message>();
for (int i = 0; i < res.Length; i++)
{
Message msg = new Message()
{
SenderID = currentUserId,
ReciverID = int.Parse(res[i]),
Subject = subject.Replace("'", ""),
Content = content.Replace("'", ""),
IsRead = false,
SendDate = DateTime.Now.ToLocalTime(),
DeletedBy = -1
};
m.Add(msg);
}
MessageService.SendList(m);
var jsonSerialiser = new JavaScriptSerializer();
Context.Response.Write(jsonSerialiser.Serialize("Message sent"));
}
catch (Exception ex)
{
var jsonSerialiser = new JavaScriptSerializer();
Context.Response.Write(jsonSerialiser.Serialize("Server Error: " + ex.Message));
}
}
MessageService.SendList method:
public static void SendList(List<Message> msgs)
{
DataTable messages = new DataTable();
messages.Columns.Add("MessageSenderID");
messages.Columns.Add("MessageReciverID");
messages.Columns.Add("MessageSubject");
messages.Columns.Add("MessageContent");
messages.Columns.Add("MessageIsRead");
messages.Columns.Add("MessageSendDate");
messages.Columns.Add("MessageDeletedBy");
for (int i = 0; i < msgs.Count; i++)
{
DataRow dr = messages.NewRow();
dr["MessageSenderID"] = msgs[i].SenderID;
dr["MessageReciverID"] = msgs[i].ReciverID;
dr["MessageSubject"] = msgs[i].Subject;
dr["MessageContent"] = msgs[i].Content;
dr["MessageIsRead"] = false;
dr["MessageSendDate"] = DateTime.Now;
dr["MessageDeletedBy"] = -1;
messages.Rows.Add(dr);
}
OleDbConnection con = new OleDbConnection(Connect.GetConnectionString());
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Messages(MessageSenderID, MessageReciverID, MessageSubject, MessageContent, " +
"MessageIsRead, MessageSendDate, MessageDeletedBy) " +
"VALUES " +
"(#MessageSenderID, #MessageReciverID, #MessageSubject, #MessageContent, #MessageIsRead, " +
"#MessageSendDate, #MessageDeletedBy)";
cmd.Parameters.Add("#MessageSenderID", OleDbType.Integer);
cmd.Parameters.Add("#MessageReciverID", OleDbType.Integer);
cmd.Parameters.Add("#MessageSubject", OleDbType.WChar, 255);
cmd.Parameters.Add("#MessageContent", OleDbType.WChar, 255);
cmd.Parameters.Add("#MessageIsRead", OleDbType.Boolean, 2);
cmd.Parameters.Add("#MessageSendDate", OleDbType.Date);
cmd.Parameters.Add("#MessageDeletedBy", OleDbType.Integer);
con.Open();
cmd.Prepare();
for (int i = 0; i < messages.Rows.Count; i++)
{
cmd.Parameters[0].Value = int.Parse(messages.Rows[i]["MessageSenderID"].ToString());
cmd.Parameters[1].Value = int.Parse(messages.Rows[i]["MessageReciverID"].ToString());
cmd.Parameters[2].Value = messages.Rows[i]["MessageSubject"].ToString();
cmd.Parameters[3].Value = messages.Rows[i]["MessageContent"].ToString();
cmd.Parameters[4].Value = bool.Parse(messages.Rows[i]["MessageIsRead"].ToString());
cmd.Parameters[5].Value = DateTime.Parse(messages.Rows[i]["MessageSendDate"].ToString());
cmd.Parameters[6].Value = int.Parse(messages.Rows[i]["MessageDeletedBy"].ToString());
cmd.ExecuteNonQuery();
}
OleDbTransaction trance = con.BeginTransaction();
cmd.Transaction = trance;
trance.Commit();
con.Close();
}
The code stuck at con.Open(); and giving: System.AccessViolationException Attempted to read or write protected memory. This is often an indication that other memory has been corrupted
I am using SQLite database for my PhoneGap project.The database is getting populated on every other OS I have tested except Android 4.4.0+ .
The Code for accessing database is below :-
public class MathWhiz extends CordovaActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
super.loadUrl(Config.getStartUrl());
SharedPreferences sp = getSharedPreferences("MYPREFS",
Activity.MODE_PRIVATE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// If no shared prefs exist, e.g. first install, it doesn't matter - the
// following will return false as a default
Boolean database_copied = sp.getBoolean("database_copied", false);
if (!database_copied) {
try {
String pName = this.getClass().getPackage().getName();
this.copy("Databases.db", "/data/data/" + pName
+ "/app_database/");
this.copy("sample.db", "/data/data/" + pName
+ "/app_database/myFile/");
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("database_copied", true);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
void copy(String file, String folder) throws IOException {
File CheckDirectory;
CheckDirectory = new File(folder);
if (!CheckDirectory.exists()) {
CheckDirectory.mkdir();
}
InputStream in = getApplicationContext().getAssets().open(file);
OutputStream out = new FileOutputStream(folder + file);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
}
And this is how I am using the database :-
window.openDatabase("sampleDB", "1.0", "sample", 200000);
Can anybody please point out what updates I need to do in order to make it work on Android 4.4 + ? Thanks
try it.. its working well...
public boolean copyDataBaseFromAssets(Context c) throws IOException {
if(android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/"+ DATABASE_NAME;
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"+DATABASE_NAME;
String pathToDatabaseFileInAssetFolder = DATABASE_NAME;
String pathToDatabaseFileInSystem = DB_PATH;
this.getReadableDatabase();
> getReadableDatabase funcation used in db import code
AssetManager assetManager = c.getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(pathToDatabaseFileInAssetFolder);
} catch (IOException ex) {
return false;
}
if (inputStream != null) {
OutputStream outputStream = new FileOutputStream(pathToDatabaseFileInSystem);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
Log.d(TAG, "Database is copied");
return true;
}
return false;
}
Change this
this.copy("Databases.db", "/data/data/" + pName + "/databases/");
this.copy("sample.db", "/data/data/" + pName + "/databases/");
I have loaded a web page in BB as follow
//RegBrowserFieldConfig extends BrowserFieldConfig
RegBrowserFieldConfig regBrowserFieldConfig = new RegBrowserFieldConfig();
//RegBrowserFieldListener extends BrowserFieldListener
RegBrowserFieldListener regBrowserFieldListener = new RegBrowserFieldListener();
BrowserField registrationBrowserField = new BrowserField(regBrowserFieldConfig);
registrationBrowserField.addListener(regBrowserFieldListener);
add(registrationBrowserField);
registrationBrowserField.requestContent("http://myurl.com/");
That web page loads fine. There is a submit button in that web page which call onsubmit in the form element in HTML. That is calling to a JavaScript function. With in that function there are some other URL that will fire according to the requirements.
What I need is to get the response of those URL calls. How can I do that?
I tried this way..
BrowserFieldListener list = new BrowserFieldListener() {
public void documentLoaded(BrowserField browserField,
Document document) throws Exception {
String url = document.getBaseURI(); //u can get the current url here... u can use ur logic to get the url after clicking the submit button
Serverconnection(url);//from this methode u can get the response
}
};
browserField.addListener(list);
Serverconnection..
public String Serverconnection(String url) {
String line = "";
// if (DeviceInfo.isSimulator()) {
// url = url + ";deviceSide=true";
// } else {
// url = url + ";deviceSide=true";
// }
url = url + getConnectionString();
try {
HttpConnection s = (HttpConnection) Connector.open(url);
s.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
s.setRequestProperty(
"Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
s.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"UTF-8");
s.setRequestMethod(HttpConnection.GET);
InputStream input = s.openInputStream();
byte[] data = new byte[10240];
int len = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
line = raw.toString();
input.close();
s.close();
} catch (Exception e) {
System.out.println("response--- excep" + line + e.getMessage());
}
return line;
}
EDIT..
private static String getConnectionString() {
String connectionString = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = "?;interface=wifi";
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = "?;&deviceside=false";
} else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
connectionString = "?;deviceside=true";
} else {
connectionString = "?;deviceside=false?;connectionUID="
+ carrierUid + "?;ConnectionType=mds-public";
}
} else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
}
return connectionString;
}
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}