Download video inside a JSON with android - android

How to download video inside JSON with android
I need to download a video encode in base 64 in android from a JSON
The JSON is something like this:
{
"status"=0
"result"="AAAAAHGZ0eXBtcDqyAAAAAG1wN...."
}
The video in the attribute result (it's more longer). I need to download the video and save it in a file.
When converting stream to string I have this error:
E/dalvikvm-heap(4964): Out of memory on a 53109242-byte allocation.
Because the file it's to big.
How I can do this? Because I can't save it in a string.
I tried this but It didn't work:
JsonReader readerJ = new JsonReader(new InputStreamReader(is, "UTF-8"));
Gson gson = new Gson();
CapraboFileRequest file = null;
readerJ.beginObject();
int id=0;
String text="";
while (readerJ.hasNext()) {
String name = readerJ.nextName();
if (name.equals("status")) {
id = readerJ.nextInt();
} else if (name.equals("result")) {
text = readerJ.nextString().substring(0, 100);}
Log.d("result", text);
file=new CapraboFileRequest(id, text);
setFile(file);

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.

Adding static JSON to an Android Studio project

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);

How to handle special characters in json string

I have an app where I store user entered text into a json string. I then store that json string into a file. And then later on display it back by reading the file, extracting the json string from it and finally getting the string to display into a textview. I am however noticing that any special characters(rather symbols) like £, ÷, € etc are not displayed back. For example the symbol € gets displayed as â□¬.
Some sample code below for reference
First the code for capturing user entered text and putting it into a file
//get user entered text
QuestionEditText = (EditText)this.findViewById(R.id.editTextQuestion);
//put that into json object
JSONObject jObjOneQuestionDetails=new JSONObject();
jObjOneQuestionDetails.put("Question", QuestionEditText.getText());
//write json object into file
FileOutputStream output = openFileOutput("MyFileName",MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(output);
writer.writejObjOneQuestionDetails.put());
writer.flush();
writer.close();
Now below the code for getting the string back from file and displaying it to user
//define and initialize variables
QuestionEditText = (EditText)this.findViewById(R.id.editTextQuestion);
private JSONArray jArrayQuizQuestions=new JSONArray();
private JSONObject jObjQuizTitle=new JSONObject();
//load JSONObject with the File
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
String fileString;
fis = this.getBaseContext().openFileInput("MyFileName");
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
fileString = new String(fileContent);
jObjQuizTitle = new JSONObject(fileString);
jArrayQuizQuestions = jObjQuizTitle.getJSONArray("MyFileName");
//display json object into textview
JSONObject aQues = jArrayQuizQuestions.getJSONObject(pageNumber-1);
String quesValue = aQues.getString("Question");
QuestionEditText.setText(quesValue.toCharArray(), 0, quesValue.length());
The code above is just a sample, I have ignored any try/catch blocks here. This should give an idea about how I am capturing and displaying the user entered text.
You have to use "UTF-8" for using this kind of special character. For details read http://developer.android.com/reference/java/nio/charset/Charset.html
You have to encode for your expected character like this way :
URLEncoder.encode("Your Special Character", "UTF8");
You can check similar question about this issue from here :
Android: Parsing special characters (ä,ö,ü) in JSON

How to parse HTML full page in android

I am calling a HTML page via a web servise . I need to get hole source code of HTML page.
My problem is that, when I convert the http response to string I am getting only some part of HTML page. How do I can get hole HTML page .Please help me.
//paramString1 = url,paramString = header, paramList = paramiters
public String a(String paramString1, String paramString2, List paramList)
{
String str1 = null;
HttpPost localHttpPost = new HttpPost(paramString1);
localHttpPost.addHeader("Accept-Encoding", "gzip");
InputStream localInputStream = null;
try
{
localHttpPost.setEntity(new UrlEncodedFormEntity(paramList));
localHttpPost.setHeader("Referer", paramString2);
HttpResponse localHttpResponse = this.c.execute(localHttpPost);
int i = localHttpResponse.getStatusLine().getStatusCode();
localInputStream = localHttpResponse.getEntity().getContent();
Header localHeader = localHttpResponse.getFirstHeader("Content-Encoding");
if ((localHeader != null) && (localHeader.getValue().equalsIgnoreCase("gzip")))
{
GZIPInputStream localObject = null;
localObject = new GZIPInputStream(localInputStream);
Log.d("API", "GZIP Response decoded!");
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader((InputStream)localObject, "UTF-8"));
StringBuilder localStringBuilder = new StringBuilder();
while(true){
String str2 = localBufferedReader.readLine();
if (str2 == null)
break;
localHttpResponse.getEntity().consumeContent();
str1 = localStringBuilder.toString();
localStringBuilder.append(str2);
continue;
}
}
}
catch (IOException localIOException)
{
localHttpPost.abort();
}
catch (Exception localException)
{
localHttpPost.abort();
}
Object localObject = localInputStream;
return (String)str1;
Are you receiving the HTML in the variable paramString1?, in that case, are you encoding the String somehow or its just plane HTML?
Maybe the HTML special characters are breaking your response. Try encoding the String with urlSafe Base64 in your server side, and decoding it in the client side:
You can use the function Base64 of Apache Commons.
Server Side:
Base64 encoder = new Base64(true);
encoder.encode(yourBytes);
Client side:
Base64 decoder = new Base64(true);
byte[] decodedBytes = decoder.decode(paramString1);
HttpPost localHttpPost = new HttpPost(new String(decodedBytes));
You may not get the complete source code in your stringBuilder as it must be exceeding the max size of stringBuilder as StringBuilder is set of arrays. If u want to store that particular sourcecode. You may try this: The inputStream (which contains html source code) data, store directly into a File. Then you will have complete source code in that file and then perform file operation to whatever you require. See if this may help you.

JSON Parsing without using URL to read json file in 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);

Categories

Resources