This question already has answers here:
How do I trim a file extension from a String in Java?
(23 answers)
Closed 9 years ago.
I got confused with substring in android. in my database i have file pdf like this DOGMATIKA-3.pdf and i want to select the "pdf". ho to do it in android? i just want to select 3 last letters , anyone please help me, thank you. i already try with this code but got force close.
package mobile.download;
public class DownloadText extends Activity{
public Koneksi linkurl;
public Kondownload linkurl2;
String url;
String SERVER_URL;
String SERVER_URL2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkdownload);
TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("keyIdc");
String param2 = bundle.getString("keyReference");
if(param2.substring(-3, 0).equals("pdf"))
{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/moodledata/"+param1+"/"+param2;
mTextLink.setText(SERVER_URL);
Pattern pattern = Pattern.compile(SERVER_URL);
Linkify.addLinks(mTextLink, pattern, "");
}
else
{
linkurl2 = new Kondownload(param2);
SERVER_URL2 = linkurl2.getUrl();
mTextLink.setText(SERVER_URL2);
Pattern pattern = Pattern.compile(SERVER_URL2);
Linkify.addLinks(mTextLink, pattern, "");
}
}
}
last 3 letters are length() - 3 to length() (the second parameter is implicitely length(), so it is not necessary)
param2.substring(params2.length() - 3)
however, you could use endsWith which is clearer :
param2.endsWith("pdf")
which does exactly that.
try param2.substring(param2.indexOf("."), param2.length()).equals("pdf") instead..
If you are intent on using .substring(), use string.substring(string.length()-3).
However, you can also use the .split() method like so:
String [] split = string.split(".");
This will create a new array excluding all instances of "." and using them as the array separators. In other words, if you called this .split() on your above string, you would get
{"DOGMATIKA-3","pdf"}
The latter method will work for file extensions that are not three characters.
i have file pdf like this DOGMATIKA-3.pdf and i want to select the
"pdf"
String test = "myPdf.pdf";
String extension = test.substring(test.lastIndexOf(".")+1, test.length());
Or you can just do :
String extension = test.substring(test.lastIndexOf(".")+1);
just use like that
String substr = param2.substring(param2.length() - 3);
if("pdf".equals(substr))
{
// use what you want
}
Related
I am doing a reading text file practice where I read and store the data into a string array object. One ArrayList data should have photo, title, website, and date. The text file looks like this:
photo:android_pie
title:Android Pie: Everything you need to know about Android 9
website:https://www.androidcentral.com/pie
date:20-08-2018
photo:oppo
title:OPPO Find X display
website:https://www.androidpit.com/oppo-find-x-display-review
date:25-08-2018
photo:android_pie2
title:Android 9 Pie: What Are App Actions & How To Use Them
website:https://www.androidheadlines.com/2018/08/android-9-pie-what-are-app-
actions-how-to-use-them.html
date:16-09-2018
I am trying to split and store them into a string array, which is an instance of my object class:
private List<ItemObjects> itemList;
and this is the constructor of my object class:
public ItemObjects(String photo, String name, String link, String date) {
this.photo = photo;
this.name = name;
this.link = link;
this.date = date;
}
I tried this but the ":" separator doesnt separate it like I want it to:
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
String[] tmpItemArr = sItems.split("\\:");
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
}
}
What is the best way of doing this? I have tried using for loop which stops at third line and adds the next one as new data. There are several online ways of doing it but some are very complicated and I am having trouble understanding it.
The problem is your understanding of using both the split function and the BufferReader.
By using readline function you are reading only one line so your split will split the first line only, you need to read the 4 first lines then add the item.
int count = 0;
String[] tmpItemArr = new String[4];
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
tmpItemArr[count] = sItems.split(":")[1];
count++;
if (count > 3) {
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
count = 0;
}
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am new to app development and I have a problem with coding in android studio. I want to compare an input text with a string in the string array. For some reason it won't work. When i try the java code in eclipse it works.
I already run the debugger and the inputmessage is "Banana". The debugger also shows that message = "Banana" when it is in CheckAnswer(message). But for some reason the function isn't returning "Right". It returns "wrong"
I hope somebody can help me.
Here is my code:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
String message2 = CheckAnswer(message);
intent.putExtra(CORRECT_MESSAGE, message2);
startActivity(intent);
}
public static String CheckAnswer(String string) {
String rightanswer[] = {"Apple", "Banana", "Coconut"};
String answer = null;
for (int i = 0; i <= rightanswer.length-1; i++) {
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
else answer = "Wrong.";
}
return answer;
}
The correct way of comparing two strings is with equals() function not ==
So Change :
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
to:
if (string.equals(rightanswer[i])) {
answer = "Right!!";
break;
}
When you are comparing Strings in Java, it is best to use the String's equals()method which looks like this:
if(someValue.equals(somethingElse){}
I hope this helps!
I'm trying to find a Java sub-string and then delete it without deleting the rest of the string.
I am taking XML as input and would like to delete a deprecated tag, so for instance:
public class whatever {
public static void main(String[] args) {
String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
CharSequence deleteRaise = "<name>";
// If an Addenda exists we continue with the process
if (xml_in.contains(deleteRaise)){
// delete
} else {
// Carry on
}
}
In there I would like to delete the <name> and </name> tags if they are included in the string while leaving <someStuff> and </someStuff>.
I already parsed the XML to a String so there's no problem there. I need to know how to find the specific strings and delete them.
You can use replaceAll(regex, str) to do this. If you're not familiar with regex, the ? just means there can be 0 or 1 occurrences of / in the string, so it covers <name> and </name>
String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
String filter = "</?name>";
uploadedXML = uploadedXML.replaceAll(filter, "");
System.out.println(uploadedXML);
<someStuff>Bats!</someStuff>
String uploadedXML = "<someStuff>Bats!</someStuff> <name></name>";
String deleteRaise = "<name>";
String closeName = "</name>"
// If an Addenda exists we continue with the process
if (xml_in.contains(deleteRaise)){
uploadedXML.replace(uploadedXML.substring(uploadedXML.indexOf(deleteRaise),uploadedXML.indexOf(closeName)+1),"");
} else {
// Carry on
}enter code here
so, right now I have this String:
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
I want to be able to get just this part of the the string but I'm at a loss as to how to do this.
Needed Output:
String[] requiredOutput;
requiredOutput[1] = 48526; // csfo_offering
requiredOutput[2] = csfo_add_ind A;
or
requiredOutput[2] = A; // csfo_add_ind
EDIT:
I have used some of your suggestions and am trying out subString but it seems like its a temp fix because if the length of the original string changes then it will throw a wrench in my calls. I will try regex next because it seems to go by pattern matching and I might be able to figure something out with that. Thanks everyone for all your help.
Suggestions are still appreciated!
Are the numbers always the same length? If so, use String.subString. If not use String.indexOf("csfo_add") to find the locations of the "csfo_add" parts and then find the relative locations of the required information.
Hi there you can also use split if you always have the same pattern for your string.
for example
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
System.out.println(csfo.split("csfo_add_ind ")[1].split("\\]\\)")[0]);
Would get the requiredOutput[2] = A; // csfo_add_ind
and this would get the first one
String[] requiredOutput = new String[2];
String csfo = "([csfo_num = 333015303][ csfo_minimum = 4044504600][ csfo_offering = 48526][csfo_add_ind A])";
requiredOutput[0] = "csfo_add_ind " + csfo.split("csfo_add_ind ")[1].split("\\]\\)")[0];
requiredOutput[1] = csfo.split("\\]\\[csfo_add_ind ")[0].split("csfo_offering = ")[1];
//System.out.println(requiredOutput[0] + " et " + requiredOutput[1] );
I'm making a an application and I want the application to automatically log in from a text file if the user has already logged in. Currently, in the text file i have "alex|ppp" which matches the database entry.
The following method is called first
private void rememberedLogIn(){
String filename = "UserInfo.txt";
String info = "";
String user = "";
String pass = "";
try{
FileInputStream fIn = openFileInput(filename);
BufferedReader r = new BufferedReader(new InputStreamReader(fIn));
info = r.readLine();
}catch(IOException e){
e.printStackTrace(System.err);
}
for(int i =0; i < info.length();i++){
if(info.charAt(i) == '|' ){
user = info.substring(0,i);
pass = info.substring(i+1);
GlobalVar.loggedIn= true;
break;
}
}
new InitialStuff().execute(user,pass);
}
I have double checked the values for user and pass and they are "alex" and "ppp" which is expected. Next InitialStuff is called, this is the relevant code:
public class InitialStuff extends AsyncTask<String, Void, Toon>{
int prog = 0;
#Override
protected Toon doInBackground(String... params) {
android.os.Debug.waitForDebugger();
Toon toon = null;
Database db = new Database();
db.establishConnection();
if(db.tryLogIn(params[0], params[1])){
prog = 2;
publishProgress();
toon = db.getToonFromDB(params[0]);
prog = 4;
}else prog = 3;
publishProgress();
return toon;
}}
The problem occurs once i call the db.tryLogin() which looks like this
public boolean tryLogIn(String toonName, String toonPass){
try{
while(!connected) establishConnection();
String sqlQuery = "SELECT Password FROM Toons WHERE Name LIKE '" + toonName+"';";
Statement stmt = con.createStatement();
ResultSet rSet = stmt.executeQuery(sqlQuery);
if(rSet.next()){
String dbPass = rSet.getString(1).trim();
if(dbPass.equals(toonPass)) //PROBLEM OCCURS HERE
return true;
}
}
catch(Exception e){ }
return false;
}
I have checked to see that dbPass comes back from the database as "ppp" which matches toonPass yet it will skip over the return true and return false instead.
If it helps, this is the information eclipse gives me about the two
toonPass "ppp" (id=830041185816)
count 3
hashCode 0
offset 5
value (id=830041185744)
[0] a
[1] l
[2] e
[3] x
[4] |
[5] p
[6] p
[7] p
dbPass "ppp" (id=830041708816)
count 3
hashCode 0
offset 0
value (id=830041709136)
[0] p
[1] p
[2] p
Pleaes note that i have also tried passing in "ppp" to the tryLogin() method without taking it as a substring in case that had something to do with the problem and the outcome is the same.
EDIT: I solved the problem...sorta. I just stopped using the .equals() method and instead am using a for loop that compares the characters in each string to one another
one hint!
if you're playing with String class methods eg. .compare() .equals() etc. remember about charset encoding! especially ensure to match with IDE, project files ,resources & db's encoding (when you load/read data as string from external sources)
if(dbPass.equals(toonPass)) //PROBLEM OCCURS HERE
Are you really sure ?
The problem is probably here:
catch(Exception e){ }
Write this instead and inspect your logs:
catch(Exception e){ e.printStackTrace(); }
Strangely, it looks like the Eclipse debugging information isn't matching. The char[] that you've printed out for toonPass looks like it reads "alex|ppp" and dbPass looks like "ppp". The offset of 5 for toonPass makes it seem like the strings are equal because it's skipped the first 5 characters ("alex|") and is thus up to "ppp".
I'd suggest rewriting the loop that splits up the "alex|ppp" from the text file. If you just want to split it on the '|' character then info.split("|") will probably do the trick.