I am getting string errors - java

After changing my string from this:
String osver = System.getProperty("os.name");
if (osver.contains("Mac")){
String app = wd + "/relap5.x\"";
} else if (osver.contains("Windows")){
String app = "relap5.exe";
} else if (osver.contains("linux")) {
String app = "/relap5.x";
}
To this:
String[] osver = {System.getProperty("os.name")};
if (osver.contains("Mac")){
String[] app = {wd + "/relap5.x\""};
} else if (osver.contains("Windows")){
String[] app = {"relap5.exe"};
} else if (osver.contains("linux")) {
String[] app = {"/relap5.x"};
}
I am getting errors.
Cannot find symbol
symbol: method contains(String)
Location variable osver of type string[]

You cannot do contains over an array.
You could alternatively do this:
List<String> osver = Arrays.asList(System.getProperty("os.name"));
if (osver.contains("Mac")) {
String[] app = { wd + "/relap5.x\"" };
} else if (osver.contains("Windows")) {
String[] app = { "relap5.exe" };
} else if (osver.contains("linux")) {
String[] app = { "/relap5.x" };
}

This is because Array does not contain method contains. Do you mean the following:
String osver = System.getProperty("os.name");
String app;
if (osver.equals("Mac")){
app = "wd" + "/relap5.x\"";
} else if (osver.equals("Windows")){
app = "relap5.exe";
} else if (osver.equals("linux")) {
app = "/relap5.x";
}
System.out.println(app);
The above code will check for equality but if you want to check for containment then use:
String osver = System.getProperty("os.name");
String app;
if (osver.contains("Mac")){
app = "wd" + "/relap5.x\"";
} else if (osver.contains("Windows")){
app = "relap5.exe";
} else if (osver.contains("linux")) {
app = "/relap5.x";
}
System.out.println(app);

Related

Error writing a file in Android 11 passing a variable as file name

I am trying to save files created in a specific directory I choose. I have many reason why I am doing this not locally.
My app had as target up to Android 10, but now I am trying to target Android 11 as well and so far everything works, except for one thing, the files are not saved if I pass a string variable as file name instead of a written name in the StringBuilder.
Let me explain you showing the working code and the not working code:
////WORKING
public class MyLoggerUtility {
private static String filename = "MyMonitoring_Log";
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();
public static void addRecordToLog(String var0) {
if ("mounted".equals(state)) {
isExternalStorageWriteable = true;
isExternalStorageAvailable = true;
} else if ("mounted_ro".equals(state)) {
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
isExternalStorageWriteable = false;
isExternalStorageAvailable = false;
}
File var1 = new File("/sdcard/MYPATH/LOG");
if ("mounted".equals(state)) {
if (!var1.exists()) {
Log.d("Dir created ", "Dir created ");
var1.mkdirs();
}
StringBuilder var6 = new StringBuilder();
var6.append("/sdcard/MYPATH/LOG/");
var6.append(filename);
var6.append(".txt");
File var2 = new File(var6.toString());
if (!var2.exists()) {
try {
Log.d("File created ", "File created ");
var2.createNewFile();
} catch (IOException var5) {
var5.printStackTrace();
}
}
try {
FileWriter var3 = new FileWriter(var2, true);
BufferedWriter var7 = new BufferedWriter(var3);
StringBuilder var8 = new StringBuilder();
var8.append(var0);
var8.append("\r\n");
var7.write(var8.toString());
var7.flush();
var7.close();
} catch (IOException var4) {
var4.printStackTrace();
}
}
}
}
And the not working one:
////NOT WORKING
public class MyLoggerUtility {
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();
public static void addRecordToLog(String var0, String fileName) {
if ("mounted".equals(state)) {
isExternalStorageWriteable = true;
isExternalStorageAvailable = true;
} else if ("mounted_ro".equals(state)) {
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
isExternalStorageWriteable = false;
isExternalStorageAvailable = false;
}
File var1 = new File("/sdcard/MYPATH/LOG");
if ("mounted".equals(state)) {
if (!var1.exists()) {
Log.d("Dir created ", "Dir created ");
var1.mkdirs();
}
StringBuilder var6 = new StringBuilder();
var6.append("/sdcard/MYPATH/LOG/");
var6.append(fileName); ================> USING THIS IT DOES NOT WRITE THE FILE
var6.append(".txt");
File var2 = new File(var6.toString());
if (!var2.exists()) {
try {
Log.d("File created ", "File created ");
var2.createNewFile();
} catch (IOException var5) {
var5.printStackTrace();
}
}
try {
FileWriter var3 = new FileWriter(var2, true);
BufferedWriter var7 = new BufferedWriter(var3);
StringBuilder var8 = new StringBuilder();
var8.append(var0);
var8.append("\r\n");
var7.write(var8.toString());
var7.flush();
var7.close();
} catch (IOException var4) {
var4.printStackTrace();
}
}
}
}
I have no idea why this does not works only in Android 11. I have all the permits, as I said it does work with the first example, the problem happens only when using the second one.
If i run the log to watch errors i get the Exception: Operation not permitted.
But it does not make any sense to me because if i use "123" instead of my variable it does create it.
Thank you in advance for everyone who will have a look.
UPDATE: Solved thanks to the user #blackapps, answer in the comments.
I was using ":" character in the file name, it was working up to Android 10 but in Android 11 it caused the file not being created.

How to open new Activity for Vcard and how to open Google Maps app?

I am making a qr code scanner app and I can't complete two things. The first one is to pass information about Vcard to a new Activity. Here is the code I wrote:
#Override
public void handleResult(Result rawResult) {
processRawResult(rawResult.getText());
}
private void processRawResult(String text){
if (text.startsWith("BEGIN:")) {
String[] tokens = text.split("\n");
QRVcardModel qrVcardModel = new QRVcardModel();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].startsWith("BEGIN:")) {
qrVcardModel.setType(tokens[i].substring("BEGIN:".length()));
} else if (tokens[i].startsWith("N:")) {
qrVcardModel.setName(tokens[i].substring("N:".length()));
} else if (tokens[i].startsWith("ORG:")) {
qrVcardModel.setOrg(tokens[i].substring("ORG:".length()));
} else if (tokens[i].startsWith("TEL:")) {
qrVcardModel.setTel(tokens[i].substring("TEL:".length()));
} else if (tokens[i].startsWith("URl:")) {
qrVcardModel.setUrl(tokens[i].substring("URL:".length()));
} else if (tokens[i].startsWith("EMAIL:")) {
qrVcardModel.setEmail(tokens[i].substring("EMAIL:".length()));
} else if (tokens[i].startsWith("ADR:")) {
qrVcardModel.setAddress(tokens[i].substring("ADR:".length()));
} else if (tokens[i].startsWith("NOTE:")) {
qrVcardModel.setNote(tokens[i].substring("NOTE:".length()));
} else if (tokens[i].startsWith("SUMMARY:")) {
qrVcardModel.setSummary(tokens[i].substring("SUMMARY:".length()));
} else if (tokens[i].startsWith("DTSTART:")) {
qrVcardModel.setDtstart(tokens[i].substring("DTSTART:".length()));
} else if (tokens[i].startsWith("DTEND:")) {
qrVcardModel.setDtend(tokens[i].substring("DTEND:".length()));
}
}
Intent intentVcard = new Intent(MainActivity.this, VcardActivity.class);
startActivity(intentVcard);
}
The second problem I face is that I can't open Google Maps app when I scan the Geoqrcode. Here is the code:
else if (text.startsWith("geo:"))
{
QRGeoModel qrGeoModel = new QRGeoModel();
String delims = "[ , ?q= ]+";
String tokens[] = text.split(delims);
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].startsWith(" geo:"))
{
qrGeoModel.setLat(tokens[i].substring("geo:".length()));
}
}
qrGeoModel.setLat(tokens[0].substring("geo:".length()));
qrGeoModel.setLng(tokens[1]);
qrGeoModel.setGeo_place(tokens[2]);
Uri gmmIntentUri = Uri.parse("qrGeoModel.getLat(),qrGeoModel.getLng()");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
Do you know how can I do that two?
You can pass values in Intent like this :
intentVcard.putExtra("value_name" , value);
value can be String, int, boolean, long and more (you can check in your ide what you can pass).
On the recieving activity you can get the value like this :
getIntent.getStrinExtra("value_name");
Be sure to replace it by your value name, for String it is like this, however for boolean it will be :
getIntent.getBooleanExtra("value_name" , defualt_value);
About the Google Maps problem, look at this line
Uri gmmIntentUri = Uri.parse("qrGeoModel.getLat(),qrGeoModel.getLng()");
you don't need " there, that way you will pass it all as a string and not the actual value of qrGeoModel.getLat(), insted write this line like that :
Uri gmmIntentUri = Uri.parse(qrGeoModel.getLat() + "," + qrGeoModel.getLng());

Error while creating new File in SD Card using DocumentFile.createFile();

I am trying to create a new File in SD Card for Android 5.0 and above. So first I am making the user grant the permission through SAF. This is how I am check if the selected Directory is SD Card or Not.
public static boolean wrong_directory_selected(Uri uri, Context con)
{
final File uri_path=new File(FileUtil.getFullPathFromTreeUri(uri,con));
if(uri_path.getName().toLowerCase().equals(new File("SD CARD PATH").getName().toLowerCase()))
{
return false;
}
return true;
}
And then this is how I am Trying to Create a new File.
DocumentFile move = DocumentFile(new File("path)).createFile(mime,"name); // But I am getting java.lang.NullPointerException
Below are the methods which I am using to get the DocumentFile for the Directory to which the file has to be Created.
public static DocumentFile DocumentFile(final File file)
{
DocumentFile rootDocFile = DocumentFile.fromTreeUri(con, permission().getUri());
String[] parts = (file.getPath()).split("\\/");
for (int i = 3; i < parts.length; i++)
{
rootDocFile = rootDocFile.findFile(parts[i]);
}
return rootDocFile;
}
public static UriPermission permission()
{
for (UriPermission permissionUri : con.getContentResolver().getPersistedUriPermissions())
{
final File uri_path = new File(FileUtil.getFullPathFromTreeUri(permissionUri.getUri(), con));
if (uri_path.getName().toLowerCase().equals(new File("SD_CARD_PATH").getName().toLowerCase()))
{
return permissionUri;
}
}
return null;
}
The code is working fine most of the time but sometime I am getting java.lang.NullPointerException.
Any Help would be Grateful.
EDIT: This is my FileUtil class
public final class FileUtil {
private static final String PRIMARY_VOLUME_NAME = "primary";
#Nullable
public static String getFullPathFromTreeUri(#Nullable final Uri treeUri, Context con)
{
if (treeUri == null)
{
return null;
}
String volumePath = FileUtil.getVolumePath(FileUtil.getVolumeIdFromTreeUri(treeUri),con);
if (volumePath == null)
{
return File.separator;
}
if (volumePath.endsWith(File.separator))
{
volumePath = volumePath.substring(0, volumePath.length() - 1);
}
String documentPath = FileUtil.getDocumentPathFromTreeUri(treeUri);
if (documentPath.endsWith(File.separator))
{
documentPath = documentPath.substring(0, documentPath.length() - 1);
}
if (documentPath.length() > 0)
{
if (documentPath.startsWith(File.separator))
{
return volumePath + documentPath;
}
else {
return volumePath + File.separator + documentPath;
}
}
else
{
return volumePath;
}
}
private static String getVolumePath(final String volumeId, Context con)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
{
return null;
}
try {
StorageManager mStorageManager =
(StorageManager) con.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getUuid = storageVolumeClazz.getMethod("getUuid");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++)
{
Object storageVolumeElement = Array.get(result, i);
String uuid = (String) getUuid.invoke(storageVolumeElement);
Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);
// primary volume?
if (primary && PRIMARY_VOLUME_NAME.equals(volumeId))
{
return (String) getPath.invoke(storageVolumeElement);
}
// other volumes?
if (uuid != null)
{
if (uuid.equals(volumeId))
{
return (String) getPath.invoke(storageVolumeElement);
}
}
}
// not found.
return null;
}
catch (Exception ex)
{
return null;
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri)
{
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if (split.length > 0)
{
return split[0];
}
else
{
return null;
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getDocumentPathFromTreeUri(final Uri treeUri)
{
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if ((split.length >= 2) && (split[1] != null))
{
return split[1];
}
else
{
return File.separator;
}
}
}
EDIT 2 :
The Path in which the file has to be created is fine and I have also checked the Permission URI and even that is not null.
The Values are
The path where the file has to be created- /storage/external_SD
Permission Uri- content://com.android.externalstorage.documents/tree/6634-3765%3A
EDIT 3:
I am using this library to find the SD Card path.
Continue from this answer now that you have the DocumentFile (which is a directory to create a file inside it) through the loop just use myDocumentFile.createFile(...) to create a new file on your desired directory.
// creating the file
DocumentFile documentFileNewFile = documentFileGoal.createFile(myMimeType,
myNewFileName);
Then stream to it
outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri());
inputStream = new FileInputStream(myInputFile);
...
if (outputStream != null) {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
}
...
...
...
} finally {
if (inputStream != null)
inputStream.close();
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
Edite
Prevent findFile on a null DocumentFile by checking the value of rootDocFile on each loop. (happens when the user selects a wrong path instead of the sd-card)
for (int i = 3; i < parts.length; i++)
{
if (rootDocFile != null) {
rootDocFile = rootDocFile.findFile(parts[i]);
}
}

RecyclerView is empty on "some" devices, but works perfectly on my own device

I have an app that uses json data to populate a recyclerview. It works perfectly on my own device. However, it doesn't work on some devices which even have the same android version with mine.
I found the source of the problem by printing the size of the ArrayList at some stages of the data handling and I am sure nothing is due to network.
The exact problem is that the ArrayList.size() returns 0 on some devices but it doesn't happen on my own device which shows "231" for the size.
The list is defined in the class and initialized in the void.
List<Match> liste;
private void refreshList() {
String ret = new TinyDB(getApplicationContext()).getString("list");
try {
JSONArray bulten = new JSONArray(ret.substring(ret.indexOf("[")));
if(ret==""){Toast.makeText(getApplicationContext(),"Something is wrong.",Toast.LENGTH_LONG).show();}
liste = new ArrayList<>();
for (int i = 0; i < bulten.length(); i++) {
String isim,kod,ust,alt,bet;
bet = bulten.optJSONObject(i).getString("BetTypeId");
isim = bulten.optJSONObject(i).getString("BetName");
kod = bulten.optJSONObject(i).getString("Code");
if(bulten.optJSONObject(i).optJSONArray("Odds25").optJSONObject(0) != null){
ust = bulten.optJSONObject(i).optJSONArray("Odds25").optJSONObject(0).getString("Value");
alt = bulten.optJSONObject(i).optJSONArray("Odds25").optJSONObject(1).getString("Value");}
else{
ust = "0.00";
alt= "0.00";
}
if(bet == "3"){
liste.add(new Match(isim,kod,ust,alt));}
}
Toast.makeText(getApplicationContext(),""+liste.size(),Toast.LENGTH_SHORT)
.show(); // The part I show the size of the arraylist is here.
Collections.sort(liste, new Match.CompId());
RecyclerView.Adapter adapter1 = new RVAdapter(liste);
rv.setAdapter(adapter1);
} catch (JSONException e) {
e.printStackTrace();
}catch (StringIndexOutOfBoundsException e){}
}
Here is the Match class:
public class Match {
String isim;
String kod;
String ust;
String alt;
Match(String isim, String kod, String ust, String alt) {
this.isim = isim;
this.kod = kod;
this.ust = ust;
this.alt = alt;
}
public static class CompId implements Comparator<Match> {
#Override
public int compare(Match arg0, Match arg1) {
return Integer.parseInt(arg0.kod) - Integer.parseInt(arg1.kod);
}
}
}
I don't know why this happened but in the line
if(bet == "3"){
liste.add(new Match(isim,kod,ust,alt));}
}
I was checking if the variable bet is equal to three. It seems that in some devices the string "3" is not read as "3". I changed this line to bet.contains("3")
and it is working right now on those devices.

how to remove 503 exceptions in java

I have a list of names in the form of a CSV and I am up for google searching those names using java. But the problem that i am facing is that when i initially run the code i am able to search the query but in the middle of the code the code starts to throw 503 exceptions and when i again run the code it starts throwing 503 exceptions from the very beginning.Here is the code that i am using.
public class ExtractInformation
{
static String firstname,middlename,lastname;
public static final int PAGE_NUMBERS = 10;
public static void readCSV()
{
boolean first = true;
try
{
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("E:\\KOLDump\\names.csv"));
String line = null;
String site = null;
while((line=br.readLine())!=null)
{
if(first)
{
first = false;
continue;
}
String[] b = line.split(splitBy);
firstname = b[0];
middlename = b[1];
lastname = b[2];
String name = null;
if(middlename == null || middlename.length() == 0)
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0);
}
else
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0)+" OR "+firstname+" "+middlename.charAt(0)+". "+lastname;
}
BufferedReader brs = new BufferedReader(new FileReader("E:\\KOLDump\\site.csv"));
while((site = brs.readLine()) != null)
{
if(first)
{
first = false;
continue;
}
String [] s = site.split(splitBy);
String siteName = s[0];
siteName = (siteName.replace("www.", ""));
siteName = (siteName.replace("http://", ""));
getDataFromGoogle(name.trim(), siteName.trim());
}
brs.close();
}
//br.close();
}
catch(Exception e)
{
System.out.println("unable to read file...some problem in the csv");
}
}
public static void main(String[] args)
{
readCSV();
}
private static void getDataFromGoogle(String query,String siteName)
{
Set<String> result = new HashSet<String>();
String request = "http://www.google.co.in/search?q="+query+" "+siteName;
try
{
Document doc = Jsoup.connect(request).userAgent("Chrome").timeout(10000).get();
Element query_results = doc.getElementById("ires");
Elements gees = query_results.getElementsByClass("g");
for(Element gee : gees)
{
Element h3 = gee.getElementsByTag("h3").get(0);
String annotation = h3.getElementsByTag("a").get(0).attr("href");
if(annotation.split("q=",2)[1].contains(siteName))
{
System.out.println(annotation.split("q=",2)[1]);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
any suggestions on how to remove this exceptions from the code would really be helpful.
If you wait a little do the 503's go away? If so, then you're probably being rate-limited by Google. https://support.google.com/gsa/answer/2686272?hl=en
You may need to put some kind of delay between requests.

Categories

Resources