I am not able to save data from file into an object.If I recover the data from the file and save them in a string, the application works, but as soon as I try to save them inside an object (a Note object in my case), I fail .
It is a simple app(similar to notepads) with only a mainActivity to manage operations, an object class that include two variable, one for "title" and another one for "text" and an xml file with two input fields, two buttons(load and save) and a textView to view the data.
This is the the mainActivity code:
public class MainActivity extends AppCompatActivity {
EditText title,text;
Button save,load;
TextView result;
ArrayList<Note> notes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.id_title);
text = findViewById((R.id.id_post));
save = findViewById(R.id.buttonSave);
load = findViewById(R.id.buttonLoad);
result = findViewById(R.id.id_result);
Context context = getApplicationContext();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titolo = title.getText().toString();
String post = text.getText().toString();
//Note nota = new Note(titolo,post);
Note nota = new Note(titolo,post);
//nota.setTitle(titolo);
//nota.setNote(post);
saveData(nota,context);
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//ArrayList<Note> data;
//String x;
//x= readData(context);
//x = data.getTitle() + " " +data.getNote();
//result.setText(x);
//setTextToTextview();
readData(context);
}
});
}
/**
* This function saves data on file
* #param nota
* #param context
*/
public void saveData(Note nota,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("text.txt", Context.MODE_APPEND));
outputStreamWriter.write(nota.getTitle().toString() + "," + nota.getNote().toString() + "\n");
outputStreamWriter.flush();
outputStreamWriter.close();
Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.getMessage();
}
}
private void setTextToTextview() {
String text = "";
for(int i = 0; i < notes.size(); i++)
{
text = text + notes.get(i).getTitle() + "" + notes.get(i).getNote() + "\n";
}
result.setText(text);
}
/**
* Read data from file
*/
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(receiveString, ",");
Note nota = new Note(token.nextToken(), token.nextToken());
notes.add(nota);
}
inputStream.close();
bufferedReader.close();
setTextToTextview();
//stringa = stringBuilder.toString();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/*******************************************************
*this work
*******************************************************/
/*
public String readData(Context context)
{
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
bufferedReader.close();
ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return ret;
}
*/
/*****************************************
* this work
*******************************************/
/*
public String readData(Context context)
{
// Note nota = new Note();
String stringa ="";
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
ret = stringBuilder.toString();
// StringTokenizer token = new StringTokenizer(ret,",");
String split[]= ret.split(",");
for(int i = 0; i< split.length;i++)
{
stringa = stringa +"," + split[i];
}
/*
nota.setTitle(split[0]);
nota.setNote(split[1]);
notes.add(nota);
*/
/*
}
inputStream.close();
bufferedReader.close();
//setTextToTextview();
//ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return stringa;
}
*/
}
I also tried like this:
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
stringa = stringBuilder.toString();
part = stringa.split(",",2);
Note nota = new Note(part[0],part[1]);
notes.add(nota);
setTextToTextview();
}
inputStream.close();
bufferedReader.close();
//stringa = stringBuilder.toString();
}
} catch (final IOException e) {
e.printStackTrace();
}
//return stringa;
}
thanks to anyone who can help me.
Related
Just tried to run and I receive this error:
JSONException: No value for courseDivide
StatisticsFragment$ByEntire.onPostExecute(StatisticsFragment.java:225)
StatisticsFragment$ByEntire.onPostExecute(StatisticsFragment.java:153)
I'm a beginner with Java and I can't seem to figure out why JSONException has No value.
The code:
class ByEntire extends AsyncTask<Void, Void, String> {
String target;
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute(){
try{
target = "http://wook1150.cafe24.com/ByEntire.php";
dialog.setMessage("로딩중");
dialog.show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(target);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp;
StringBuilder stringBuilder = new StringBuilder();
while ((temp = bufferedReader.readLine()) !=null)
{
stringBuilder.append(temp + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Void... values){
super.onProgressUpdate();
}
#Override
public void onPostExecute(String result){
try{
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("response");
int count = 0;
int courseID;
String courseGrade;
String courseTitle;
String courseProfessor;
int courseCredit;
int courseDivide; //////Error here//////
int coursePersonnel;
String courseTime;
while(count < jsonArray.length()){
JSONObject object = jsonArray.getJSONObject(count);
courseID = object.getInt("courseID");
courseGrade = object.getString("courseGrade");
courseTitle = object.getString("courseTitle");
courseProfessor = object.getString("courseProfessor");
courseCredit = object.getInt("courseCredit");
courseDivide = object.getInt("courseDivide)");
coursePersonnel = object.getInt("coursePersonnel)");
courseTime = object.getString("courseTime)");
rankList.add(new Course(courseID, courseGrade, courseTitle, courseCredit, courseDivide, coursePersonnel,courseTime, courseProfessor));
count++;
dialog.dismiss();
}
rankListAdapter.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
}
}
}
Might be your JSON doesnt have courseDivide or mistyping, remove the ')'
courseDivide = object.getInt("courseDivide");
coursePersonnel = object.getInt("coursePersonnel");
courseTime = object.getString("courseTime");
please help me out from this i need to display the json array data but it will only show the first value from json .i tried to change the values but one value is shown not an array
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnadd=(Button)findViewById(R.id.btnhit);
tvdata = (TextView)findViewById(R.id.tvJsonitem);
btnadd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.myjson.com/bins/106o37");
}
}
);
}
public class JSONTask extends AsyncTask{
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
StringBuffer finalBufferedData=new StringBuffer();
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String description = obj.getString("description");
finalBufferedData.append(description + "\t\n"
);
return finalBufferedData.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Your return statement should be outside of your for loop. Now it is inside so the method returns the first value.
use this
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
StringBuffer finalBufferedData=new StringBuffer();
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String description = obj.getString("description");
finalBufferedData.append(description + "\t\n"
);
}
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
I'm using socket to create http socket server on Java android application.
Send and Get headers from client and server I'm getting fast. But get when trying read http body it takes a long time... why ?
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
public void run() {
try {
runProxy();
}catch (Throwable t){
}
};
}).start();
}
private void runProxy() throws Throwable{
try {
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new TestProxy(s)).start();
}
}catch (IOException e){
}
}
TestProxy.class
public class TestProxy implements Runnable{
private Socket s, c;
private InputStream is;
private OutputStream os;
ArrayList<String> requestList;
ArrayList<String> responseList;
private BufferedReader br;
public TestProxy(Socket s) throws Throwable{
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
this.requestList = new ArrayList<String>();
this.responseList = new ArrayList<String>();
this.run();
}
public void run(){
try {
this.readRequest();
this.forwardRequest();
this.forwardResponse(); //<--- this is trouble ??!
}catch (Throwable e){
}finally {
/*try {
s.close();
c.close();
}catch (IOException e) {}*/
}
}
private void readRequest() throws Throwable{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//int lengthBody = 0;
while(true) {
String s = br.readLine();
requestList.add(s + "\r\n");
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null || s.trim().length() == 0) {
break;
}
}
is.close();
}
private void forwardRequest(){
String firstSectionInProtocol = requestList.get(0); //GET http://example.com/?d=d HTTP/1.1
Pattern p = Pattern.compile("^\\w+\\s+(\\S+)");
Matcher m = p.matcher(firstSectionInProtocol);
if(m.find()) {
String URI = m.group(1); //http://example.com/?d=d
try {
URL aURL = new URL(URI);
try {
c = new Socket(aURL.getHost(), 80);
final OutputStream outToServer = c.getOutputStream();
String firstSection = "GET "+aURL.getFile()+" HTTP/1.1\r\n";
outToServer.write(firstSection.getBytes());
System.out.println(firstSection);
for(int i = 1; i < requestList.size(); i++){
outToServer.write(requestList.get(i).getBytes());
System.out.println(requestList.get(i));
}
outToServer.flush();
}catch (IOException e) {
}
}catch (MalformedURLException e){ }
}
}
private void forwardResponse() throws Throwable{
final InputStream inFromServer = c.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer));
int lengthBody = 0;
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}
if(s.equals("")) {
break;
}
}
//
// Processing long time
//
if (lengthBody > 0) {
int read;
StringBuilder body = new StringBuilder();
while ((read = br.read()) != -1) {
body.append((char) read);
if (body.length() >= lengthBody)
break;
}
System.out.println(body.toString());
}
}
}
in the method forwardResponse(); i trying get a body response.
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null) {
break;
}
}
I have a problem. When I do a query in the stream, I have downloaded the data from the URL, everything works. But when I call AsynsTask example by pressing doInBackground() method that returns the same data, but they are updated on the URL. And they will not be updated as long as the program is restarted.
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
All code
public class ParseTask extends AsyncTask<Void, Void, String> {
int intRow = 0;
String jSON_R = "";
private List<User> movieList;
Activity act;
ListView list;
LAdapter adapter;
boolean Unique = true;
public ParseTask (Activity act){
this.act = act;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
list = (ListView) act.findViewById(R.id.listVew);
Button b = (Button) act.findViewById(R.id.refresh);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//To do
}
});
movieList = new ArrayList<>();
adapter = new LAdapter(act, movieList);
list.setAdapter(adapter);
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 1){
Unique = false;
}else{
Unique = true;
}
}
});
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true){
sleep(5000);
if (Unique){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Update();
}
});
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void Update(){
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
Calling the object in such a way
new ParseTask(getActivity()).execute();
Close the connection.
I mean use (better) reader.close() or inputStream.close()
Or try jsoup library https://jsoup.org/
I am trying to read more than one rss link from the xml source txt file in the code below. I am using ; as the delimiter. From debug, it seems to be sending all the links to RSS_LINK, which is obviously not going to work.
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line) ;
}
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
New Code
protected void onHandleIntent(Intent intent)
{
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line) ;
}
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
String RssLink = arr[i];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RssLink));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
}
catch (IOException e)
{
e.printStackTrace();
}
You split the rsslink's but instead of using the resulting arr you continue to work with rsslink which still has all links and ; combined.
You need to put all rss handling (parsing etc) into the loop:
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
// HERE IS THE PLACE TO HANDLE a single RSS Link. arr contains the single link
}