I'm storing some values in a text file and each line looks like that, Cellid: -----, LAC: ------, Lat: ------, Long: --------- what I want to do is to compare the cellid that the phone currently operates, with the cellids from the text file and if it matched then print a marker in google maps. My question is how navigate in the text file while reading it. The file is stored in the phones sdcard.
Try this
First: add these in public area
public static final String Key_Cellid = "Cellid";
public static final String Key_LAC = "LAC";
public static final String Key_Lat = "Lat";
public static final String Key_Long = "Long";
ArrayList<HashMap<String,String>> values = new ArrayList<HashMap<String, String>>();
then add this method to seperate name and value for each item:
public void stringExtracter(String st){
String mainStr = st;
int items = 4; // Numbers of items in each line
HashMap<String,String> hash = new HashMap<String, String>();
for(int i=0; i<items; i++){
String num="";
int sep = mainStr.indexOf(":");
String fst = mainStr.substring(0, sep);
mainStr = mainStr.replaceFirst(fst+":", "");
if(i<items - 1){
sep = mainStr.indexOf(",");
num = mainStr.substring(0, sep);
mainStr = mainStr.replaceFirst(num+",", "");
}
else{
num = mainStr;
//mainStr = mainStr.replaceFirst(num+",", "");
}
hash.put(fst, num);
}
values.add(hash);
}
Now edit your code :
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
stringExtracter(line);
}
//here you can get only numbers from text and convert it to integer then compare it
}
catch (IOException e) {
//You'll need to add proper error handling here
}
Know you can get data from values
array list like:
for(int i=0;i<values.size();i++){
HashMap<String,String> hash = values.get(i);
System.out.println(hash.get(Key_Cellid));
System.out.println(hash.get(Key_LAC));
System.out.println(hash.get(Key_Lat));
System.out.println(hash.get(Key_Long));
System.out.println("--------------");
}
Important Note:
I assumed no space in each line in text file
Cellid:123,LAC:456,Lat:223,Long:213
I stored numbers as string because that you should convert it to Integer or Double or what you want to using it in map.
Hope this help you.