Using stringbuilder and bufferedreader to read more than one link - java

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
}

Related

Data management from file in Android

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.

Reading music from asset folder

My project is list of music that user can set as ringtone.
All of my music is located in raw and it works correctly and also my ringtone name is a text in raw "zeallist".
My problem is that how to put my music in asset folder.
Here is my code that play music from raw:
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
How to change this part of my code to read them from asset and return my listsong ?
Core part I have finished.Some details you need do yourself
public ArrayList<SongInfo> getAllSong(Context context) throws IOException {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(context);
String[] files = context.getAssets().list("Your songs path");
for (int i = 0; i < files.length - 1; i++) {
SongInfo info = new SongInfo();
String name = files[i];
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
/* int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);*/ //fileName is enough to you
}
// info.setName(name);
listSong.add(info);
}
InputStream inputStream = context.getAssets().open("Your zeallist path");
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
When you want to play corresponding music, you could do like this
public void play(MediaPlayer mediaPlayer, Context context, String musicName) throws IOException {
AssetFileDescriptor assetFileDescriptor = context.getAssets().openFd(musicName);
mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
}
Hope this will solve your problem .
Right click on res folder and Create new folder called raw. Now copy paste few .MP3 files inside it. Check those links for better understanding.
link1
link2
From Assest folder
public void playBeep() {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.setVolume(1f, 1f);
mp.setLooping(true);
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
You can read file from asset using AssetManager
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.

This code will get only first value from json string

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

A long time read body of request to http server with Socket

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

Cannot convert to JSON Array

I tried to convert JSON from PHP server side to string in Android.
It force closes with (java.lang.String cannot be converted to JSONObject ) Error.
This is my Web class for HTTP connecting:
public class Web {
public static String readUrl(String url) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputstreamToString(inputStream);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String convertInputstreamToString(InputStream inputStream){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line ="";
while ((line = reader.readLine())!=null) {
builder.append(line);
}
return String.valueOf(builder);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String result = Web.readUrl("http://192.168.1.53/mana/mana%20records.php");
if (result != null) {
try {
JSONArray records = new JSONArray(result);
for (int i = 0; i < records.length(); i++) {
JSONObject record = records.getJSONObject(i);
Log.d("Records", record.getString("date"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
And this is my JSON:
[{"date":"2015-12-01","Shift Day":"on","Shift Night":"",
"Shift Person":"a","Code":"1","1st":"1000","Size 8":null,
"2nd":"1","3rd":"10","logo":"1000","Storage":"10000"},
{"date":"2015-12-02","Shift Day":"",
"Shift Night":"on","Shift Person":"b","Code":"2","1st":"2000",
"Size 8":null,"2nd":"2","3rd":"20","logo":"2000",
"Storage":"20000"}]

Categories

Resources