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);
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.
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
I'm doing some tests with Gson parser to Json objects and object model.
There is one thing that I can't understand, why Reader can read once?
Code example:
Reader targetReader = new StringReader(jdb);
String targetString = "";
try {
int intValueOfChar;
while ((intValueOfChar = reader.read()) != -1) {
targetString += (char) intValueOfChar;
}
} catch (IOException e) {
e.printStackTrace();
}
JsonParser jp = new JsonParser();
JsonObject jason = jp.parse(reader).getAsJsonObject();
JsonArray votes_a = jason.getAsJsonArray("votesA");
JsonArray votes_b = jason.getAsJsonArray("votesB");
In this code the first while goes perfect, reads and writes to String but then I want to read it and parset to Object but the reader is empty!!
is there a way to keep the information, and recycle it?
Do I have to clone it before? how?
Because when you read from the reader, it moves a pointer along what you're reading. So after reading through it once, you're already at the end of what you're reading. Take a look at the reset() method of StringReader.
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.
How to show the letters like ø æ å in android Application, I want to show these characters in Full Project, Please Help How i Do it ?
When the strings are read from a JSON document make sure to decode the JSON file correctly. That is, know the character encoding that was used for creating the JSON files and use that same encoding when decoding the files.
Assuming you already have an InputStream for reading your JSON document you can use something like this:
private static final Charset JSON_CHARSET = Charset.forName("UTF-8");
private JSONObject loadJsonObject(InputStream in) throws JSONException, IOException {
InputStreamReader reader = new InputStreamReader(in, JSON_CHARSET);
StringWriter writer = new StringWriter();
copy(reader, writer);
return new JSONObject(writer.toString());
}
private static void copy(Reader reader, Writer writer) throws IOException {
try {
char[] buffer = new char[512];
while (true) {
int nChars = reader.read(buffer);
if (nChars < 0) {
break;
}
writer.write(buffer, 0, nChars);
}
} finally {
reader.close();
writer.close();
}
}
Use a charset other than UTF-8 if necessary.
How about using Charset.forName("UTF-8").encode(myString) ? Naturally, strings should be stored in external resources string.xml, so mystring should be eg.
String mystring = getString(R.string.myStringResource);
I found I had to change the XML attribute of my layout file to UTF16 to get certain extended characters to display correctly.
<?xml version="1.0" encoding="UTF-16"?>
put the special strings.xml under the res/value-xxx/