I want to get SDCard ID.
I am getting problem in Nougat(7.0) and above OS.
I already tried this,
private String getExternalSdCARDId() {
try {
String exsdcard_path = "/sys/block/mmcblk1";
File file = new File(exsdcard_path);
String memBlk = null;
if (file.exists() && file.isDirectory()) {
memBlk = "mmcblk1";
} else {
System.out.println("not a directory");
memBlk = "mmcblk0";
}
Process cmd = Runtime.getRuntime().exec("cat /sys/block/" + memBlk + "/device/cid");
BufferedReader br = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
return br.readLine();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
But this method returns NULL.
try this :
String path2 = "/sys/block/mmcblk0/device";
BufferedReader serial;
BufferedReader name ;
BufferedReader manfid;
BufferedReader oemid;
BufferedReader mfDate;
BufferedReader CID;
serial = new BufferedReader(new FileReader(path2 + "/serial"));
name = new BufferedReader(new FileReader(path2 + "/name"));
manfid = new BufferedReader(new FileReader(path2 + "/manfid"));
oemid = new BufferedReader(new FileReader(path2 + "/oemid"));
mfDate = new BufferedReader(new FileReader(path2 + "/date"));
CID = new BufferedReader(new FileReader(path2 + "/cid"));
String sdSerial = serial.readLine();
String sdName = name.readLine();
String sdMfId = manfid.readLine();
String sdOemId = oemid.readLine();
String sdMfDate = mfDate.readLine();
String sdCid = CID.readLine();
or also use this
File input = new File("/sys/class/mmc_host/mmc1");
String cid_directory = null;
int i = 0;
File[] sid = input.listFiles();
for (i = 0; i < sid.length; i++) {
Log.d(TAG,"sid info "+sid[i]);
if (sid[i].toString().contains("mmc1:")) {
cid_directory = sid[i].toString();
String SID = (String) sid[i].toString().subSequence(cid_directory.length() - 4, cid_directory.length());
Log.d(TAG, " SID of MMC = " + SID);
break;
}
}
BufferedReader serial = new BufferedReader(new FileReader(cid_directory + "/serial"));
BufferedReader name = new BufferedReader(new FileReader(cid_directory + "/name"));
BufferedReader manfid = new BufferedReader(new FileReader(cid_directory + "/manfid"));
BufferedReader oemid = new BufferedReader(new FileReader(cid_directory + "/oemid"));
BufferedReader mfDate = new BufferedReader(new FileReader(cid_directory + "/date"));
BufferedReader CID = new BufferedReader(new FileReader(cid_directory + "/cid"));
String sdSerial = serial.readLine();
String sdName = name.readLine();
String sdMfId = manfid.readLine();
String sdOemId = oemid.readLine();
String sdMfDate = mfDate.readLine();
String sdCid = CID.readLine();
//make sure before using this code check sdcard is present or not;
Above 7.0:Use
StorageVolume.getUuid()on StorageVolume which you get from StorageManager.
The value is volume ID assigned during formatting of the card, and its length/format differs depending on file system type. For FAT32 it is XXXX-XXXX, for NTFS it's longer hex string, for Internal mass storage it returns null.
Related
I've an asynctask , this is the code inside background :
try {
URL url = new URL(urls);
Log.v("this", urls);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineC;
StringBuffer sb = new StringBuffer();
while ((lineC = bufferedReader.readLine()) != null)
{
sb.append(lineC );
}
Log.v("this",sb.toString() + " I need this for something else");
NodeList nodes = doc.getElementsByTagName("data");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("content");
Element line = (Element) title.item(0);
if (i == 0)
random = line.getTextContent();
else if (i == 1)
topsell = line.getTextContent();
else if (i == 2)
jadidtarin = line.getTextContent();
else if (i == 3)
pishnahad = line.getTextContent();
}
} catch (Exception e) {
e.printStackTrace();
goterror = true;
Log.v("this", e.getMessage() + "eror");
}
When I remove these lines , it works fine and I get no problem.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineC;
StringBuffer sb = new StringBuffer();
while ((lineC = bufferedReader.readLine()) != null)
{
sb.append(lineC );
}
I don't close anything but when I run the code, I get this error "Stream is closed" , I don't know why .
How can I solve this problem ? as I said in the code, I need to save the whole returned value .
How can I solve this problem ?
Instead of using:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Use
BufferedReader bufferedReader = new BufferedReader(new BufferedInputStream(conn.getInputStream()));
I want to store these values to server.
The data which i have to store is complete in the variables.
I should get
{"response":{"result":1,"Message":"Poll Entered Successfully."}}
from server
but getting -1
#Override
protected String doInBackground(String... params) {
String jsonString = null;
HttpURLConnection linkConnection = null;
try {
String squestion = question.getText().toString();
String shashtag = hashTag.getText().toString();
spolltime = polltime.getText().toString();
StringBuilder scat = new StringBuilder();
scat.append("");
scat.append(categoryid);
StringBuilder sid = new StringBuilder();
sid.append("");
sid.append(LoginPage.logid);
//int ipolltime = Integer.parseInt(spolltime);
String equestion = URLEncoder.encode(squestion,"UTF-8");
String ehashtag = URLEncoder.encode(shashtag,"UTF-8");
String ecategory = URLEncoder.encode(scat.toString(),"UTF-8");
String eA = URLEncoder.encode(OptionA.stext,"UTF-8");
String eB = URLEncoder.encode(OptionB.stext,"UTF-8");
String eC = URLEncoder.encode(OptionC.stext,"UTF-8");
String eD = URLEncoder.encode(OptionD.stext,"UTF-8");
String eid = URLEncoder.encode(sid.toString(),"UTF-8");
String epolltime = URLEncoder.encode(spolltime,"UTF-8");
URL linkurl = new URL("http://iipacademy.in/askpoll/pollfeeds.php?user_id="+eid+"&question="+equestion+
"&hashtag="+ehashtag+"&category_id="+ecategory+"&option1="+eA+"&option2="+eB+"&option3="+eC+"&option4="+eD+"" +
"&pollopen="+epolltime+"&optiontype1=texty&optiontype2=texty&optiontype3=texty&optiontype4=texty");
linkConnection = (HttpURLConnection) linkurl.openConnection();
int responseCode = linkConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream linkinStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkinStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (linkConnection != null) {
linkConnection.disconnect();
}
}
//Toast.makeText(getApplicationContext(),jsonString.toString(),
//Toast.LENGTH_LONG).show();
return jsonString;
}
I am not able to find my mistake !
thanks
first of all try to make this call from browser and check for response . there is an extension
on chrome PostMan rest client. please check first. may be you are not getting the response correctly.
I am trying to parse Vcard file. here is my code.
public void get_vcf_data(String file) throws VCardException, IOException{
VCardParser parser = new VCardParser();
VDataBuilder builder = new VDataBuilder();
//String file = path;
//read whole file to string
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
String vcardString = "";
String line;
while ((line = reader.readLine()) != null) {
vcardString += line + "\n";
}
reader.close();
//parse the string
boolean parsed = parser.parse(vcardString, "UTF-8", builder);
if (!parsed) {
throw new VCardException("Could not parse vCard file: " + file);
}
//get all parsed contacts
List<VNode> pimContacts = builder.vNodeList;
//do something for all the contacts
for (VNode contact : pimContacts) {
ArrayList<PropertyNode> props = contact.propList;
//contact name - FN property
String name = null;
String number = null;
String tel = null;
for (PropertyNode prop : props) {
if ("FN".equals(prop.propName)) {
name = prop.propValue;
Contact_name.add(name);
Log.d("Name", name);
//we have the name now
break;
}
}
for (PropertyNode prop : props) {
if ("N".equals(prop.propName)) {
number = prop.propValue;
Contact_number.add(number);
Log.d("Name", number);
//we have the name now
break;
}
}
for (PropertyNode prop : props) {
if(" TEL".equals(prop.propName))
{
tel = prop.propValue;
Contact_tel.add(tel);
Log.d("Name", tel);
}
}
Log.d("Tag", ""+Contact_name.size()+"::"+Contact_number.size()+"::"+Contact_tel.size());
//similarly for other properties (N, ORG, TEL, etc)
//...
System.out.println("Found contact: " + name);
}
}
but facing problem in while loop
while ((line = reader.readLine()) != null) {
vcardString += line + "\n";
}
continuously looping inside a while loop and doesn't exit from loop once it is entered
i am reading a file using the following code
`FileReader fr=new FileReader("/mnt/sdcard/content.csv");
BufferedReader in = new BufferedReader(fr);
String reader = "";
while ((reader = in.readLine()) != null){
String[] RowData = reader.split(",");
id = RowData[0];
path = RowData[1];`
and i have also tried using the opencsv class but with both the method i am only able to read the last entry in the file..
what am i missing?can someone explain to me?
FileReader fr=new FileReader("/mnt/sdcard/playlist_record.csv");
BufferedReader in = new BufferedReader(fr);
String reader = "";
while ((reader = in.readLine()) != null){
String[] RowData = reader.split(",");
id = RowData[0];
path = RowData[1];
type= RowData[2];
update= RowData[3];
server= RowData[4];
t1.setText(id);
// t1.append(path);
// t1.append(type);
// t1.append(server);
}
in.close();
this is my code i am using to read the file
I'm trying to get a csv file from http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2 then parse it so that I can get the price and the price changed into an object that sets both properties. Is there a way that I can do this with the android libraries?
Edit: Here's the current state of the union (not working):
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(uri);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
String[] RowData = result.split("\n");
String name = RowData[0];
String price = RowData[1];
String change = RowData[2];
stock.setPrice(Double.parseDouble(price));
stock.setTicker(name);
stock.setChange(change);
}
Try something like this:
//--- Suppose you have input stream `is` of your csv file then:
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1];
// do something with "data" and "value"
}
}
catch (IOException ex) {
// handle exception
}
finally {
try {
is.close();
}
catch (IOException e) {
// handle exception
}
}
Hope this helps.
For the first part:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
For the second part, Harry is right, just follow his code, or use some libraries: http://commons.apache.org/sandbox/csv/
CSVReader reader = new CSVReader(** Insert your Reader here **);
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
A better CSV parser handles quoted fields
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
private class StringDArray {
private String[] data=new String[0];
private int used=0;
public void add(String str) {
if (used >= data.length){
int new_size= used+1;
String[] new_data=new String[new_size];
java.lang.System.arraycopy( data,0,new_data,0,used);
data=new_data;
}
data[used++] = str;
}
public int length(){
return used;
}
public String[] get_araay(){
return data;
}
}
private Context context;
public CSVReader(Context context){
this.context=context;
}
public List read(InputStream inputStream){
List resultList = new ArrayList();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String csvLine;
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
while ((csvLine = reader.readLine()) != null) {
//String[] row = csvLine.split(",");// simple way
StringDArray a=new StringDArray();
String token="";
csvLine+=Separator;
for(char c:csvLine.toCharArray()){
switch (c){
case LF: case CR:// not required as we are already read line
quote_open=false;
a.add(token);
token="";
break;
case Delimiter:
quote_open=!quote_open;
break;
case Separator:
if(quote_open==false){
a.add(token);
token="";
}else{
token+=c;
}
break;
default:
token+=c;
break;
}
}
if(a.length()>0 ) {
if(resultList.size()>0){
String[] header_row =(String[]) resultList.get(0);
if(a.length()>=header_row.length) {
String[] row = a.get_araay();
resultList.add(row);
}
}else{
String[] row = a.get_araay();
resultList.add(row);//header row
}
}
}
inputStream.close();
}catch (Exception e){
Toast.makeText(context,"Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
return resultList;
}
}
Usage
File file=new File(path);
CSVReader csvReader=new CSVReader(activity.this);
List csv=csvReader.read( new FileInputStream(file));
if(csv.size()>0){
String[] header_row =(String[]) csv.get(0);
if(header_row.length>1){
String col1=header_row[0];
String col2=header_row[1];
}
}
Toast.makeText(activity.this,csv.size() + " rows", Toast.LENGTH_LONG).show();
Sample data used
ID,Name
1,Test Item 1
"2","Test Item 2"
"3","Test , Item 3"
4,Test Item 4