FileOutputStream error - fileoutputstream

I had a part of code which suppose to get an image from website and store it into the sdcard. The following code was working find when i develop on sdk1.5. However, it was not working now after i change it to android sdk 2.0. This line got problem; FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);
Here is the code that i have:
void downloadFile(String fileUrl) {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(filepath + "/"
+ this.filename);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
Context context = this.getBaseContext();
new MediaScannerNotifier2(context, filepath + "/" + this.filename,
"image/jpeg");
// displaying download completion message
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Wallpaper Downloaded").setCancelable(false)
.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
btn_setwall.setEnabled(true);
btn_download.setEnabled(false);
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}
}
The error occur in the 3rd catch. However, when i move this line
FileOutputStream fos = new
FileOutputStream(filepath + "/" +
this.filename);
to the 2nd try/catch, then it will occur in the 2nd catch.
Can please help me on this?

Maybe try getting rid of .getAbsolutePath()
This works for me on 2.2:
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);

Related

How to print from Android Studio Barcode printer

Barcode I want to send a barcode to the printer. I tried it in PDF, JPEG, PNG format. It prints a blank page on all of them.I couldn't find any results on google.
I need to do it without using Printer Helper, if possible
public class yazdır extends AsyncTask<Void , Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
DataOutputStream outToServer;
Socket clientSocket;
File filename;
PrintHelper photoPrinter = new PrintHelper(getActivity());
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
for (int i=0;i<=adet;i++) {
try {
String path = Environment.getExternalStorageDirectory().toString();
filename = new File(path + "/folder/subfolder/image.png");
FileInputStream fileInputStream = new FileInputStream(filename);
InputStream is = fileInputStream;
clientSocket = new Socket("192.168.1.31", 9100);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[1024];
int size;
while ((size=is.read(buffer)) !=-1){
outToServer.write(buffer,0,size);
}
outToServer.flush();
} catch (ConnectException connectException) {
Log.e(TAG, connectException.toString(), connectException);
return null;
} catch (UnknownHostException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} catch (IOException e1) {
Log.e(TAG, e1.toString(), e1);
return null;
} finally {
}
}
return null;}
}
When I send it to a regular printer. Says document is printing and cancels printing.

System.out.println displays blank line

Why does the below 'System.out.println'(fileEncodedString) display a blank line while the value is there when I debug and I do get an output when I decode the value and print.
byte[] fileContent = readFileToByteArray(filePath);
String fileEncodedString = Base64.getEncoder().encodeToString(fileContent);
byte[] fileDecodedString = Base64.getDecoder().decode(fileEncodedString);
System.out.println("Base64 Decoded File (Basic): " + new String(fileDecodedString, "utf-8"));
private static byte[] readFileToByteArray(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
// read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
Try to use below method for readFileToByteArray and pass correct file path:
static byte[] readFileToByteArray(String filePath) throws IOException {
File file = new File(filePath);
return Files.readAllBytes(file.toPath());
}
its working fine.

FileInputStream issue - App has stopped working

I am having trouble with FileInputStream in Android Studio. My application has stopped working when I use it to read file .txt in the internal memory (I have writen data to this file successfully). I have try many solutions but they didn't work. Can anyone give the solution for this problem? Here is my code. Thanks very much. (I have added users-permission "WRITE_EXTERNAL_STORAGE" and "READ_EXTERNAL_STORAGE").
String fileName = "infoProfile.txt";
private int readData() {
try {
String path = MainActivity.this.getFilesDir().getAbsolutePath() + "/" + fileName;
FileInputStream in = openFileInput(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
ArrayList<String> str = new ArrayList<>();
String data = "";
while ((data = reader.readLine()) != null) {
str.add(data);
}
in.close();
if (str.isEmpty())
return 0;
etName.setText(str.get(0));
etEmail.setText(str.get(1));
etPhone.setText(str.get(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

json string is not properly shown in android device

i am facing a issue on getting JObject, my app is working in emulator and it is not working in device. because the string is not properly converting to JObject.
E/JSON 1111﹕ parsing data {"success":1,"projects":[{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"3 mins","updated_at":"0000-00-00 00:00:00","keywords":"law,white sheet,pen,pencil,mini bulbs,","materials":"pen,pencil,ball,worksheet","description":"about the law bla bla","subject":"science","target":"k2","created_at":"2015-08-14 14:24:54","pid":"1","rating":"4","procedure":"procedure about this project"},{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"3 mins","updated_at":"0000-00-00 00:00:00","keywords":"pen,pencil,color pencil,chart,sticks","materials":"pen,pencil,color pencil,chart,sticks,etc","description":"about description of the project","subject":"science","target":"k3","created_at":"2015-08-14 14:25:16",
"pid":"2","rating":"3","procedure":"about description of the procedure"},{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"5 mins","updated_at":"0000-00-00 00:00:00","keywords":"pen,pencil,wire,chart,sticks","materials":"pen,pencil,color pencil,chart,sticks,eraser","description":"about description of the project","subject":"english","target":"k4","created_at":"2015-08-14 14:25:21",
....
"pid":"8","rating":"3","procedure":"about description of the procedure"}]}
the above is the output of the jsonObject, the below is the correct result showing in emulator
{"projects":[{"pid":"1","target":"k2","subject":"science","description":"about the law bla bla","duration":"3 mins","materials":"pen,pencil,ball,worksheet","procedure":"procedure about this project","keywords":"law,white sheet,pen,pencil,mini bulbs,","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"4","created_at":"2015-08-14 14:24:54","updated_at":"0000-00-00 00:00:00"},{"pid":"2","target":"k3","subject":"science","description":"about description of the project","duration":"3 mins","materials":"pen,pencil,color pencil,chart,sticks,etc","procedure":"about description of the procedure","keywords":"pen,pencil,color pencil,chart,sticks","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"3","created_at":"2015-08-14 14:25:16","updated_at":"0000-00-00 00:00:00"},
...
{"pid":"8","target":"k3","subject":"english","description":"to learn english tenses","duration":"3 mins","materials":"white sheet,pen,pencil,eraser","procedure":"about description of the procedure","keywords":"english,grammer,tenses","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"3","created_at":"2015-08-18 06:45:28","updated_at":"0000-00-00 00:00:00"}],"success":1}
this is my jsonparse class code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String jboolean = "0";
static JSONArray jarr =null;
// 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) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000 + 12000);
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type","application/json");
httpPost.setParams(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params));
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;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("Buffer 11", "Error converting result " + e.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("Buffer 22", "Error converting result " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Buffer 33", "Error converting result " + e.toString());
}
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");
}
is.close();
json = sb.toString();
//Log.e("JSON 1111 ", "parsing data " + json.toString());
} catch (Exception e) {
Log.e("Buffer Error????", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.e("JSON 1111 ", "parsing data " + jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser44", "Error parsing data " + e.toString());
}
return jObj;
/// This JObj is not properly getting the json string???
// return JSON String
}
}
Is there any issues on the above code? i am facing a issue on getting JObject, my app is working in emulator and it is not working in device. because the string is not properly converting to JObject.

SharePoint List Service Recursive not working

I am using the following code to retrieve the documents in a list. Its working fine. However, it only returns documents and folders in root of the doc library. Is there any thing wrong I am doing here? I am looking for files in sub folders with recursive mode.
Service service = new Service();
service.setMaintainSession(true);
call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL("<host>/_vti_bin/lists.asmx") );
call.setOperationName(new QName("http://schemas.microsoft.com/sharepoint/soap/","GetListItems"));
call.setProperty(Call.SOAPACTION_USE_PROPERTY, new Boolean("true"));
call.setProperty(Call.SOAPACTION_URI_PROPERTY,"http://schemas.microsoft.com/sharepoint/soap/GetListItems");
call.addParameter(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/", "listName"),
new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"),
java.lang.String.class,
javax.xml.rpc.ParameterMode.IN);
MessageElement me =
new MessageElement(new QName("QueryOptions"));
me.addChildElement(new MessageElement(new QName(
"IncludeMandatoryColumns"))).addTextNode("true");
me.addChildElement(new MessageElement(new QName(
"ViewAttributes"))).addAttribute(javax.xml.soap.SOAPFactory.newInstance().createName("Scope"), "Recursive");
MessageElement[] me1 = {me};
String strMyString = ""
+ "<Query>"
+ "<OrderBy><FieldRef Name=\"ows_Modified\" Ascending=\"TRUE\" /></OrderBy>"
+ "</Query>";
MessageElement[] meArray = { getMeFromString(strMyString) };// Array
call.addParameter("query",org.apache.axis.Constants.XSD_SCHEMA,
javax.xml.rpc.ParameterMode.IN);
call.addParameter("queryOptions",org.apache.axis.Constants.XSD_SCHEMA,
javax.xml.rpc.ParameterMode.IN);
call.setReturnType(org.apache.axis.Constants.XSD_SCHEMA);
Schema ret = (Schema)call.invoke(new Object[] {"listGUID",meArray, me1 });
public org.apache.axis.message.MessageElement getMeFromString(final String strMyString) {
DocumentBuilder docBuilder = null;
try {
docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (final ParserConfigurationException e) {
e.printStackTrace();
} catch (final FactoryConfigurationError e) {
e.printStackTrace();
}
final StringReader reader = new StringReader(strMyString);
final InputSource inputsource = new InputSource(reader);
Document doc = null;
try {
doc = docBuilder.parse(inputsource);
} catch (final SAXException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
final Element ele = doc.getDocumentElement();
final MessageElement msg = new MessageElement(ele);
return msg;
}
query.ViewAttributes = "Scope='RecursiveAll'"

Resources