I have 4 EditTExt, i write data to 1 file. But I don't know solution read data to load again for 4 EditTExtagain?
public void onClickLoad(View view) {
try
{
FileInputStream fIn =
openFileInput("textfile.txt");
InputStreamReader isr = new
InputStreamReader(fIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0,
charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been
//Can I load data for some textbox in here
//textBox1.setText(s);
textBox.setText(s);
Toast.makeText(getBaseContext(),
"File loaded successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
You can try for writing the data into the JSON format.
Which is light weight and provide you ease to read data according to the EditText and if in future your EditTexts are increased/decreased it will be easy for you to add/remove data from file.
lets take sample:
JSONObject dataToFile = new JSONObject();
dataToFile.put("EditText1","My Data1");
dataToFile.put("EditText2","My Data2");
dataToFile.put("EditText3","My Data3");
dataToFile.put("EditText4","My Data4");
//Convert JSON to String
String dataToBeWritten = dataToFile.toString();
//Code to Write data to file.
When you are reading data from file. Read it as a String.
String dataReadFromFile = //Code to Read data from file.
JSONObject dataFromFile = new JSONObject(dataReadFromFile);
String editText1Text = dataFromFile.get("EditText1");
editText1.setText(editText1Text);
.
.
.
//Till you read all the data
Related
When I read the JSON file from local or internet, It's only a few of line can read. It should be returned the Whole json file but didn't return it. Plz, give me a solution.
Example:
Link of API: https://confutable-colon.000webhostapp.com/api.php
/* there have 200 more lines on the file but show only a few of lines*/
String json = null;
InputStream is =
context.getAssets().open("info.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
Log.d("Full JSON",json);
return json;
Android Logcat can display only upto 4000 characters after that it'll split.
To show your complete Log use a custom fuction to display log just like
public static void CompleteLog(String tag, String content) {
if (content.length() > 4000) {
Log.d(tag, content.substring(0, 4000));
largeLog(tag, content.substring(4000));
} else {
Log.d(tag, content);
}
}
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'm building a simple Android application that sends items by json to a python web service for storage in a sqlite database. This part works fine and when recalled the items have their correct 'åäö' characters.
When I put these items in a json to return to the application (using code below) I'm not so sure any more. Instead of 'ö' I get '\xc3\xb6', which I believe would be the utf-8 representation?
connection = sqlite3.connect('database.db')
connection.text_factory = str
cursor = connection.cursor()
cursor.execute("SELECT item, number FROM Items")
rows = cursor.fetchall()
jsobj = []
for row in rows:
jsobj.append({'number':row[1], 'item':row[0]})
When I parse the json object in my app I'm not able to turn the '\xc3\xb6' back into 'ö'
This is the Android code at work:
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(super.url);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
JSONArray itemsOnServer = new JSONArray();
itemsOnServer = new JSONArray(reader.readLine());
return itemsOnServer;
Result sent into another function:
ArrayList<Vara> varor = new ArrayList<Vara>();
String vara = "";
int antal;
for (int i = 0; i < json.length(); i++) {
JSONObject object;
try {
object = json.getJSONObject(i);
try {
try {
vara = new String(object.getString("vara").getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} System.out.println(vara);
antal = object.getInt("antal");
varor.add(new Vara(vara, antal));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return varor;
Everything works fine except the special characters. Please help, I'm going nuts.
b'\xc3\xb6' is a bytestring that can be decoded into Unicode string that contains a single U+00f6 LATIN SMALL LETTER O WITH DIAERESIS Unicode codepoint:
>>> b'\xc3\xb6'.decode('utf-8')
u'\xf6'
By default text_factory is set to unicode for sqlite3 i.e., you should receive Unicode string for TEXT objects if you remove connection.text_factory = str from your code.
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
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.