Runtime error on Integer.parseInt(); i am trying to compare the content in the file and the new value obtained from the method - exception

/*the below code is i am trying for the notification of new mail i am trying to fetch the prestored value into the file and compare it to the new value from the method
public static void main(String args[]) throws MessagingException{
try {
Notification n= new Notification();
int a =n.Notification();
BufferedReader br = null;
//read from the earlier file value of the total messages
String sCurrentLine;
br = new BufferedReader(new FileReader("Notification.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
int b = Integer.parseInt(sCurrentLine);
if (a>b){
System.out.println("you have "+(a-b)+" new Messsages");
}else{
System.out.println("NO New message");
}
//write the new value of the total messages to the file
Writer output = null;
File file = new File("Notification.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(String.valueOf(a));
output.close();
} catch (IOException ex) {
Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
}
}

If the file you are reading from only contains a number that you require, maybe this is what you have to do:
if ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
int b = Integer.parseInt(sCurrentLine);
// do other stuff
}
else
{
// file empty
}

Related

How to write test result in CSV file using selenium

I have to add result at the last column of each row. I have to test user successfully login with correct email and password the "PASS" is append to last else "FAIL" and go with the second row and check the result of each row.
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium Drivers\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.facebook.com");
// This will load csv file
CSVReader reader = null;
try{
reader = new CSVReader(new FileReader("C:\\Users\\src\\com\\elements\\demo.csv"));
}catch (Exception e) {
e.printStackTrace();
}
String[] cell;
while ((cell=reader.readNext())!=null){
for(int i=0;i<1;i++){
String emailid=cell[i];
String password=cell[i+1];
driver.findElement(By.id("email")).sendKeys(emailid);
driver.findElement(By.id("pass")).sendKeys(password);
driver.findElement(By.id("loginbutton")).click();
String outputFile = "C:\\Users\\src\\com\\elements\\demo.csv";
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
if(driver.getTitle().equals("Log1 in to Facebook | Facebook"))
{
csvOutput.write("Pass"); //Your selenium result.
//csvOutput.endRecord();
//csvOutput.close();
}
else if (driver.getTitle().equals("Log in to Facebook | Facebook"))
{
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try this code.
String outputFile = "test.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists){
csvOutput.write("result");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Pass/Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
OR
If we want to use writeNext() method which take string array as a parameter then
String csv = "D:\\test.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Try other option.
FileWriter writer = new FileWriter("D:/test.csv",false);
writer.append(" ");
writer.append(',');
writer.append("UserName");
writer.append(',');
writer.append("Password");
writer.append(',');
writer.append("Pass/Fail");
writer.append('\n');
//generate whatever data you want
writer.flush();
writer.close();

getting java.nio.BufferUnderflowException while reading dbf file after using dbaseFileWriter.write(vals);

I'm using DbaseFileReader and DBaseFileWriter to read and update records in a dbf file. When I read the file first there is no error while opening DBF file but after I write some values to DBF using below method I'm getting the following Error
I've checked the value types in Object[] array, both type and count of values are equal to dbf file fields.
public static boolean updateFeatureAtts(String shpFile, Map<String, Object> attsFeature) throws IOException {
String file = CN.getMapDataFolder() + CN.FOLDER_LAYERS + "/" + shpFile.replace(".shp", ".dbf");
DbaseFileWriter dbaseFileWriter = null;
DbaseFileReader dbaseFileReader = null;
ReadableByteChannel dbfChannel = null;
WritableByteChannel writableByteChannel = null;
FileOutputStream fileOutputStream = null;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
dbfChannel = Channels.newChannel(inputStream);
dbaseFileReader = new DbaseFileReader(dbfChannel, true, Charset.forName("Windows-1256"));
DbaseFileHeader header = dbaseFileReader.getHeader();
for (Iterator<Map.Entry<String, Object>> iterator = attsFeature.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Object> entry = iterator.next();
if (entry.getKey().equals("FID")) {
iterator.remove();
}
}
fileOutputStream = new FileOutputStream(file);
writableByteChannel = Channels.newChannel(fileOutputStream);
dbaseFileWriter = new DbaseFileWriter(header, writableByteChannel, Charset.forName("UTF-8"), TimeZone.getDefault());
Object[] vals = attsFeature.values().toArray();
dbaseFileWriter.write(vals);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null)
inputStream.close();
if (fileOutputStream != null)
fileOutputStream.close();
if (dbaseFileReader != null)
dbaseFileReader.close();
if (dbaseFileWriter != null)
dbaseFileWriter.close();
}
return true;
}
this is the error
java.nio.BufferUnderflowException at
java.nio.DirectByteBuffer.get(DirectByteBuffer.java: 164)
at org.geotools.data.shapefile.dbf.DbaseFileReader.read(DbaseFileReader.java: 417)
at org.geotools.data.shapefile.dbf.DbaseFileReader.readRow(DbaseFileReader.java: 314)
at com.edsab.gedat.util.DBaseFileHandler.findRecord(DBaseFileHandler.java: 174)
at com.edsab.gedat.adapter.AttributePagerAdapter.instantiateItem(AttributePagerAdapter.java: 102)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java: 1003)
at android.support.v4.view.ViewPager.populate(ViewPager.java: 1217)
at android.support.v4.view.ViewPager.populate(ViewPager.java: 1085)
at android.support.v4.view.ViewPager$3.run(ViewPager.java: 273)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java: 777)
at android.view.Choreographer.doCallbacks(Choreographer.java: 590)
at android.view.Choreographer.doFrame(Choreographer.java: 559)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java: 763)
at android.os.Handler.handleCallback(Handler.java: 739)
at android.os.Handler.dispatchMessage(Handler.java: 95)
at android.os.Looper.loop(Looper.java: 145)
at android.app.ActivityThread.main(ActivityThread.java: 6918)
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: 1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 1199)

Converting finalBufferData into img url to display

I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.

How to retrieve array in php from Mysql and bind it to android

I want to retrieve some data from mysql in php and store it in array and then in Android I want to use that data. For example I want to retrieve the location of multiple people whose profession id = 1 (let's say) and then in Android I want to show that locations on map. I don't know how to do this. I have the following PHP and Android files which don't work. Please help.
<?php
require "config.php";
$pro_id=1;
$sql="SELECT user.first_name, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
//$sql = "select * from current_location where user_id=76";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('lat'=>$row[3],
'lan'=>$row[4]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
and android activity
public void searchProfession(){
JSONObject myJson = null;
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
// p.setParameter("user", "1");
p.setParameter("profession",SearchProfession);
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://abh.netai.net/abhfiles/searchProfession.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//fffffffffffffffffffffffffff
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// 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");
}
result = sb.toString();
myJSON=result;
// return JSON String
if(inputStream != null)inputStream.close();
//ffffffffffffffffffffffffffff
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(myJSON);
JSONArray jArray = json.getJSONArray("result");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String lat = e.getString("lat");
String lan = e.getString("lan");
map.put("lat",lat);
map.put("lan",lan);
mylist.add(map);
Toast.makeText(MapsActivity.this, "your location is"+lat+","+lan, Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
Dear imdad: The Problem lies in you json file.
{"[]":{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}, {"user_id":"76","crtloc_lat":"34.769604","crtloc_lng":"72.361092"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}}
The Object is empty give it some name like here is response. Change it as:
{"response":[{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769604","crtloc_lng":"72.361092"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]}

How to get the HTML source of a page from a HTML link in Android?

I'm working on an application that needs to get the source of a web page from a link, and then parse the html from that page.
Could you give me some examples, or starting points where to look to start writing such an app?
You can use HttpClient to perform an HTTP GET and retrieve the HTML response, something like this:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
I would suggest jsoup.
According to their website:
Fetch the Wikipedia homepage, parse it to a DOM, and select the headlines from the In the news section into a list of Elements (online sample):
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");
Getting started:
Download the jsoup jar core library
Read the cookbook introduction
This question is a bit old, but I figured I should post my answer now that DefaultHttpClient, HttpGet, etc. are deprecated. This function should get and return HTML, given a URL.
public static String getHtml(String url) throws IOException {
// Build and set timeout values for the request.
URLConnection connection = (new URL(url)).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// Read and store the result line by line then return the entire string.
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder html = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
html.append(line);
}
in.close();
return html.toString();
}
public class RetrieveSiteData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
StringBuilder builder = new StringBuilder(100000);
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
builder.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
}
}
Call it like
new RetrieveFeedTask(new OnTaskFinished()
{
#Override
public void onFeedRetrieved(String feeds)
{
//do whatever you want to do with the feeds
}
}).execute("http://enterurlhere.com");
RetrieveFeedTask.class
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return HTML_response;
}
#Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
OnTaskFinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}
If you have a look here or here, you will see that you can't do that directly with android API, you need an external librairy...
You can choose between the 2 here's hereabove if you need an external librairy.
One of the other SO post answer helped me. This doesn't read line by line; supposingly the html file had a line null in between. As preRequisite add this dependancy from project settings "com.koushikdutta.ion:ion:2.2.1" implement this code in AsyncTASK. If you want the returned -something- to be in UI thread, pass it to a mutual interface.
Ion.with(getApplicationContext()).
load("https://google.com/hashbrowns")
.asString()
.setCallback(new FutureCallback<String>()
{
#Override
public void onCompleted(Exception e, String result) {
//int s = result.lastIndexOf("user_id")+9;
// String st = result.substring(s,s+5);
// Log.e("USERID",st); //something
}
});
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
result += inputLine;
}
br.close();
return result;
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("https://www.example.com").get();
}catch (Exception e){
e.printStackTrace();
}
Log.i("Result", result);
}