JSON Parsing without using URL to read json file in android - android

I am using url to take the file for parsing. Now i want read the file which is in sdcard for parsing.How can i do this?
here my code
reading file from url
private static String url = "http://10.0.2.2/device1.json";
JSONObject json = jParser.getJSONFromUrl(url);
devices = json.getJSONArray(TAG_DEVICES);
now i want do this from reading the file in sdcard
java.io.File device = new java.io.File("/mnt/sdcard/device1.json");
FileReader device_Fr = new FileReader(device);
next how to pass this file for parsing?

Use this code
read data from file into string & pass that to JSONObject.
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line, results = "";
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
JSONObject obj = new JSONObject(results);

One way to do it is to read the json and store it in a string. Then parse it like this:
String jsonStr = // read from file
JSONObject json = new JSONObject( jsonStr);
// parse
 
  devices = json.getJSONArray(TAG_DEVICES);

Related

how to retrieve data from URL which is not a JSON object into android listView?

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.

Parsing json object from google api returning null

I am making a simple application where i scan the barcode of a book and fetch its title and author from Google APIs,
Now, this is the url for json(for a particular book i am scanning)
https://www.googleapis.com/books/v1/volumes?q=isbn:9788120305960
using this code to get json in a string
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
response+=line;
}
bufferedReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("Info",response);
return response;
I store the result in a string and use this code to parse through
(json_response is a string)
JSONObject rootObject = new JSONObject(json_response);
JSONArray items = rootObject.getJSONArray("items");
JSONObject items_object = items.getJSONObject(0);
JSONObject volume_info = items_object.getJSONObject("volumeInfo");
book.setTitle(volume_info.getString("title"));
JSONArray authors = volume_info.getJSONArray("authors");
Log.d("Info","authors array length: "+authors.length());
String author="";
for (int i =0;i<authors.length();i++)
{
author+=authors.getString(i)+", ";
}
book.setAuthor(author);
The exception is:
Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
also I used logcat to see what is contained in json_response it looks something like this
null{ "kind": "books#volumes", "totalItems": 1, "items":...
The null here is probably causing the problem, so... any insights how to deal with this???
PS: I am a student , dealing first time with json and android, code is unprofessional, please pardon :)
Having
null{ "kind": "books#volumes", "totalItems": 1, "items":...
means that the response value has not been initialised.
You should therefore initialise it to empty string.

Create JSON Object from Local JSON File

How do I create a "JSONObject" from a local JSON file inside my "raw" folder.
I have the following JSON file under the "raw" folder of my android app project. The file is called "app_currencies.json". I need the information contained on this file as an object in my class. Below are the file contents:
{
"EUR": { "currencyname":"Euro", "symbol":"EUR=X", "asset":"_European Union.png"},
"HTG": { "currencyname":"Haitian Gourde", "symbol":"HTG=X", "asset":"ht.png"},
"WST": { "currencyname":"Samoan Tala", "symbol":"WST=X", "asset":"ws.png"},
"GBP": { "currencyname":"British Pound", "symbol":"GBP=X", "asset":"gb.png"}
}
I think what I need is to use the following:
//Get data from Json file and make it available through a JSONObject
InputStream inputStream = getResources().openRawResource(R.raw.app_currencies.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JSONObject jObject = new JSONObject;
jObject is what I need. I think I need an InputStream, ByteArrayOutputStream so that I can store it into JSONObject... the problem is that I'm not sure how to implement this code properly so that I can access the data? If any of you could give detailed instructions on how to do this, I would really appreciate it.
The following code reads a json file into a Json Array. See if it helps. Note, the file is stored in Assets instead
BufferedReader reader = null;
try {
// open and read the file into a StringBuilder
InputStream in =mContext.getAssets().open(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// line breaks are omitted and irrelevant
jsonString.append(line);
}
// parse the JSON using JSONTokener
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
// do something here if needed from JSONObjects
for (int i = 0; i < array.length(); i++) {
}
} catch (FileNotFoundException e) {
// we will ignore this one, since it happens when we start fresh
} finally {
if (reader != null)
reader.close();
}

how get return value from node js to android?

I create android apps as client and node as server, i got problem when i request value from android to node, i use this code in android to communicate with node js
String xResult = getRequestJSON("http://mydomain.com:8888");
public String getRequestJSON(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =requestJSON(response);
}catch(Exception ex){
}
return sret;
}
public static String requestJSON(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
and i got result like this in node.
[{"posid":"P0S6f50b314b2c279a2083cb0ef821ccb4d20140218120720","id_a":"ltv#ltv.com","gambar_a":"6f50b314b2c279a2083cb0ef821ccb4d.jpg","user":"lutfi soe","pwaktu":"2014-02-18T05:07:20.000Z","posnya":"test dr android","plat":-7.983757710988161,"plong":112.6549243927002,"pjenis":"I","vote":0}]
my question is,how i receive json like that in android ?and parse to string?
thanks
If you are receiving Json string in proper format then you can use JSON jar to parse this json.
You can get a tutorial for JSON parsing here
I think your question is more on how to parse and access the result in java[read Android].
Here is a solution that could help JavaScript type arrays in JAVA
JsonArray yourArray = new JsonParser()
.parse("[[\"2012-14-03\", 2]]")
.getAsJsonArray();
// Access your array like so - yourArray.get(0).getAsString();
// yourArray.get(0).getAsInt() etc
The above is using a library called Gson
P.S: I just plagiarized my own answer. Not sure what criteria to use to mark this question as a duplicate

android Json parser offline

I'm new to the android world and i have some problem.
I'm developing a project under android and it require a json parser. I get my json file from a web service developed under Zend framework, the link to the web service : "manganew:8080/wsmanganew/manga/manga/idmanga/1" and the content of the json file is
{
"manga": [
{
"idmanga":"1",
"titre":"naruto",
"episode":"145",
"url":"http:\/\/naruto.com\/",
"image":null,
"description":"Naruto Shippuuden .",
"tv":"TV Tokyo",
"dtdebut":"2013-05-23 12:30:00",
"iduser":"1"
}
]}
I'm following this tutorial "http://www.androidhive.info/2012/01/android-json-parsing-tutorial/".
i don't know how index to the web service link in the android, any help will be useful.
thank you
so, what do you need to do? download json object from that url into your app?
that code has method getJSONFromUrl in it's class, you should use it
though, according to comments it has flaws in it.
to read string from file use this code
BufferedReader reader = new BufferedReader(new FileReader("/mnt/sdcard/docs/file.json"));
String line, results = "";
while( (line = reader.readLine()) != null)
results += line;
reader.close();
JSONObject obj = new JSONObject(results);
replace path with path to your file
try this
BufferedReader reader = new BufferedReader(new FileReader("C:\\file.json"));
String line, results = "";
while( (line = reader.readLine()) != null)
results += line;
reader.close();
JSONObject obj = new JSONObject(results);
Replace with your local machine download field path C:\\file.json

Categories

Resources