I am getting two strings and trying to check If string A contains string B. but the problem is I am getting the error The method contains(String) is undefined for the type StringBuilder. what is this error? and how do I fix this?
// 1) get saved link
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String LINK = preferences.getString("random54", "");
// 2) get text from savedlinks.txt to string
String sdcard = Environment.getExternalStorageDirectory() + "/X ADB/";
File file = new File(sdcard, "savedlinks.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
}
// 3) check if link already present in the .txt file or not
if (text.contains(LINK)) {
// DONT SAVE CAUSE DUPLICATE
} else {
// SAVE LINK IN HISTORY
Text is a StringBuilder, not a String.
if (text.toString().contains(LINK))
text.toString().contains(LINK)
StringBuilder class doesn't have contains().
Use toString() to convert to string first.
text.toString().contains(LINK)
For example
If we want to know if stringvalue contains a spotify url:
boolean contains = stringvalue.toLowerCase().contains("https://open.spotify.com/");
you can use toString() method on any java object to get a string representation of it and you can even override this method in any class to provide your own toString implementation.
In your case:
text.toString().contains(LINK)
will do the work (here you are using the toString method of StringBuilder which returns a string representing the data in this sequence)
Note: not all toString returns an expected string especially with arrays and complicated objects
Related
I have This URL and I want to fetch all the data present in here in an android list view, I only know how to retrieve data from a JSON object but here I don't even know the format of this data present in the URL.
The format of the URL is:
tvg-logo = url of the logo chanel
group-title = category where you need to display the channel (just for movie not for TV)
After the "," you have the name of the channel
And after the name you have the URL of video
How can I parse my data from the URL so that I can make a list view like that:
i think, you must split the String text by special characters. and keep them in an array. for example,the special character might be "[space character]" or "," or "#".
I hope to help you
This function will get the data from URL and you could split your data as per your requirement and populate UI.
void fetchDataFromUrl() {
try {
URL oracle = new URL("http://cinecosta.com/api_tv.php?pass=yojeju123");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The result seems easy to parse actually.Just see the pattern.
#SOMETHING tvg-logo="logo" tvg-categorie="something"
Use regex for split the pattern you want.
Regex
if you are using retrofit as a network library so you can pass the "ResponseBody" in the api callback function. In onSuccess Method We will get the Body And Use the Following the Code.
Interface Class:
Call<ResponseBody> yourFuncationName();
ResponseBody data = (ResponseBody) model.body();
String json = getStringData(data.byteStream());
Function is
public String getStringData(InputStream inputStream) {
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
try {
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}
return total.toString();
}
Maybe this will helpful for you.
Try with below code, Here I am extracted only url from the api response
String strData = "#EXTM3U #EXTINF:-1 tvg-logo=\"http://www.cinecosta.com/image-appletv/tv/tf1-tv.png\" tvg-categorie=\"TV\",TF1 http://217.182.164.103:25461/live/YnAmpNBQUX/YUCgme6CXS/314.ts #EXTINF:-1 tvg-logo=\"http://www.cinecosta.com/image-appletv/tv/france2.png\" tvg-categorie=\"TV\",France 2 http://217.182.164.103:25461/live/YnAmpNBQUX/YUCgme6CXS/315.ts #EXTINF:-1 tvg-logo=\"http://www.cinecosta.com/image-appletv/tv/france3.png\" tvg-categorie=\"TV\",France 3 http://217.182.164.103:25461/live/YnAmpNBQUX/YUCgme6CXS/316.ts #EXTINF:-1 tvg-logo=\"http://www.cinecosta.com/image-appletv/tv/france4.png\" tvg-categorie=\"TV\",France 4 http://217.182.164.103:25461/live/YnAmpNBQUX/YUCgme6CXS/317.ts #EXTINF:-1 tvg-logo=\"http://www.cinecosta.com/image-appletv/tv/france5.png\" tvg-categorie=\"TV\",France 5 http://217.182.164.103:25461/live/YnAmpNBQUX/YUCgme6CXS/318.ts";
private void convertDataToArray() {
String[] splitArray = strData.split("#EXTINF:-");
ArrayList<String> arrstrUrl = new ArrayList<String>();
ArrayList<String> arrstrMainUrl = new ArrayList<String>();
ArrayList<String> arrstrCategory = new ArrayList<String>();
ArrayList<String> arrstrName = new ArrayList<String>();
for (int i = 1; i < splitArray.length; i++) {
System.out.println("Final=>" + splitArray[i]);
arrstrUrl.add(splitArray[i].split("1 tvg-logo=")[1].split(" ")[0]);
arrstrMainUrl.add("http" + splitArray[i].split("1 tvg-logo=")[1].split("tvg-categorie=")[1].split("http")[1]);
arrstrName.add(splitArray[i].split("1 tvg-logo=")[1].split("tvg-categorie=")[1].split(",")[0]);
arrstrCategory.add(splitArray[i].split("1 tvg-logo=")[1].split("tvg-categorie=")[1].split(",")[1].split("http")[0]);
}
System.out.println("Final Image=>" + arrstrUrl.toString());
System.out.println("Final Main=>" + arrstrMainUrl.toString());
System.out.println("Final Name=>" + arrstrName.toString());
System.out.println("Final Category=>" + arrstrCategory.toString());
}
So this way, you can get parse your data and update your listview.
Note:- You need to write your own logic to parse this data, by checking data pattern.
The solution for this is :
Either you can scrap the data from python libraries like scrapy or beautiful soup then convert it to json and read from the android.
Parse the html using the jsoup lib (https://jsoup.org/) and model the data in the desire format that you want.
This is related to a situation I find myself in working with saving text files in Unity on Android, then reading them in native Android.
One of the files we read is a HMACMD5 signature, created with the code,
byte[] bData = System.Text.Encoding.UTF8.GetBytes (data);
byte[] bKey = System.Text.Encoding.UTF8.GetBytes (key);
using (HMACMD5 hmac = new HMACMD5(bKey)) {
byte[] signature = hmac.ComputeHash (bData);
return System.Convert.ToBase64String (signature);
}
And then written to the phone with,
public static void SaveText (string path, string data) {
using (FileStream fs = new FileStream(path, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
sw.Write (data);
}
}
}
The other string we're saving is a JSON string dump. The signature has a newline character at the end of the string, but the JSON string doesn't. I know I can manually add one, but this question is about reading the accurate file contents.
On Android, based on previous SO answers, I read the file with,
String readFile(File file) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
}
catch (IOException e) {
MyLogger.e(LOG_TAG, "Error opening file " + file.getPath(), e);
}
return text.toString();
}
I'm manually adding the newline character after every line, but if I do this, I don't accurately read the JSON file, which doesn't have a newline character at the end. If I don't add the newline, I don't accurately read the signature file, which does.
You better then do not use readLine() but read().
I'd like to add static JSON to an Android Studio project which can then be referenced throughout the project. Does anyone know the best method of doing this?
In more detail what I'm trying to do is this:
1) Pull data out of the Google Places API
2) Find Google places that match with places in a static JSON object
3) Place markers on a map based on the matches
I have numbers 1 and 3 working, but would like to know the best way of creating a static (constant) JSON object in my project and using it for step 2.
The answer posted above is indeed what I'm looking for, but I thought I'd add some of the code I implemented to help others take this problem further:
1) Define JSON object in a txt file in the assets folder
2) Implement a method to extract that object in string form:
private String getJSONString(Context context)
{
String str = "";
try
{
AssetManager assetManager = context.getAssets();
InputStream in = assetManager.open("json.txt");
InputStreamReader isr = new InputStreamReader(in);
char [] inputBuffer = new char[100];
int charRead;
while((charRead = isr.read(inputBuffer))>0)
{
String readString = String.copyValueOf(inputBuffer,0,charRead);
str += readString;
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return str;
}
3) Parse the object in any way you see fit. My method was similar to this:
public void parseJSON(View view)
{
JSONObject json = new JSONObject();
try {
json = new JSONObject(getJSONString(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
//implement logic with JSON here
}
You can just place your JSON file into assets folder. Later on you'll be able to read the file, parse it and use values.
You should replace the String datatype to StringBuilder in the while loop for the properly optimized solution.
So in the while loop instead of concatenating you would append the readString to the str StringBuilder.
str.append(readString);
I have a file stored in my phone "SaveTT.txt" . Every word in the file is seperated by spaces. i wish to retrieve each word from the file and display every word in seperate textViews. How to do this. please help
I am able to retrieve the contents of the file into a string with the following code
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("SAVETT.txt")));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
//EditText txt = (EditText) findViewById(R.id.temp);
//txt.setText(inputString);
}
} catch (IOException e) {
e.printStackTrace();
}
with this code get the entire string into inputString
after this . i am tokenizing the string with the following code
StringTokenizer tokenizer = new StringTokenizer(inputString);
String[] arr = new String[tokenizer.countTokens()];
while(tokenizer.hasMoreElements())
{
arr[i]= tokenizer.nextToken();
i++;
}
with the above code i am trying to save eack token in an array. Next I try to display the text in Textviews.
I dont know where i am goig wrong. the activity is stopped and a NullPointer exception is displayed.
I Figured out the problem myself. The problem was that the value of inputString is inaccessible from outside the Try catch block since it is set inside the block;
so if i write the string tokenisation block inside try catch it works perfectly fine
I want to read a txt file that contains a lot of different chunks of text separated by a string. In xcode this is pretty easy and i just use.
self.Array = [text componentsSeparatedByString: #"NEWSTRING"];
I don't seem to get this to work in android though, I can read in the whole text and put it into an array but it doesn't get separated so its just one long text.
I am using this code
AssetManager mngr;
String line = null;
boolean skillcheck = false;
StringBuffer sb = new StringBuffer(0);
String[] bb = null;
tester = new ArrayList <String>();
try {
mngr = getAssets();
InputStream is = mngr.open("mytext.txt");
InputStreamReader sir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(sir);
while((line=br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
tester.add(sb);
br.close();
} catch (IOException e1) {
}
Any good ways to do this?
You can use String.split method
String[] result = text.split("sometext");
For your acknowledgement
String.split returns the array of strings computed by splitting this
string around matches of the given regular expression
You should use StringTokenizer.
StringTokenizer sTok=new StringTokenizer(stringVariable, "newString");
while(sTok.hasMoreTokens())
System.out.println(sTok.nextToken());
stringVariable is the file contents and newString is the delimiter string.
EDIT
The second parameter of the StringTokenizer's constructor is the delimiter. It can be a new line \n or comma , or whatever you want.