How to split parsed String data without special characters? - java

I parsed this data from Wikipedia and trying to get only characters from here. But the result comes with \n* in the front of data.
"": "=== 고양이의 종류 ===\n [[시암고양이]]\n* [[페르시안 네브스카야]]\n* [[페르시안]]\n*
[[노르웨이지언 포레스트]]\n* [[터키시 앙고라]]\n* [[아메리칸 숏헤어]]\n* [[브리티시 숏헤어]]\n*
[[러시안블루]]\n* [[뱅갈]]\n* [[메인쿤]]\n* [[랙돌]]\n* [[히말라얀]]\n* [[재패니즈
밥테일]]\n* [[오리엔탈 숏헤어]]\n* [[피터볼드]]\n* [[스코티시 폴드]]\n* 스코티시 스트레이트\n*
[[하일랜드 폴드]]\n* [[시베리안 포레스트]]\n* [[터키시 반]]\n* [[코리안 쇼트헤어]]\n*
[[올블랙]]\n* [[사바나캣]]\n* [[쿠나]]\n* [[아비시니안]]\n* 먼치킨"
This is my code.
try {
URL url = new URL("https://ko.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=20&titles=%EA%B3%A0%EC%96%91%EC%9D%B4&format=json");
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
while(true){
String data = reader.readLine();
if(data == null) break;
result += data;
}
JSONObject obj = new JSONObject(result);
JSONObject query = (JSONObject) obj.get("query");
JSONObject pages = (JSONObject) query.get("pages");
JSONObject pageid = (JSONObject) pages.get("93349");
JSONArray revisions = (JSONArray) pageid.get("revisions");
String catcat = String.valueOf(revisions);
String star = "\n*";
catcat = catcat.replaceAll("\\[\\[","").replaceAll("\\]\\]",",").replaceAll("\\r|\\n", "").replaceAll(star,"");
String[] catcategory = catcat.split(",");
for (int i = 0; i<catcategory.length;i++){
list.add(catcategory[i]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Result for this looks like
\n시암고양이
\n페르시안
and I want to remove \n*.

How to split parsed String data without special characters?
Try this piece of code, It's removed \n* , Then you can add _result_word to your list.
for (int i = 0; i < catcategory.length; i++) {
try {
String _result_word = catcategory[i].replaceFirst("\\\\n", "").replace("*", "");
//String _result_word=catcategory[i].replaceFirst("\\\\n", "").replace("*", "").replaceFirst("\\\\n", "").replace("*", "");
System.out.println("" + _result_word);
list.add(_result_word);
} catch (Exception ex) {
System.out.println("Special Exception occurred at index : i = " + i);
ex.printStackTrace();
}
}

Everything correct except one line where you need escape asterisk character and escape slash character
String star = "\\\\n\\*";
str.replaceAll(star, "");

Related

Fetching array from json not working

Currently I am working with a project where I need to get some data from remote server as JSON then need to extract array. Here I am getting data successfully, But problems are near while loop.
I am getting data from remote server successfully.
For example my remote url giving output as:
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},
{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}`
Code
try {
ur = "http://localhost/getsample.php";
URL url = new URL(ur);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line !=null){
line = bufferedReader.readLine();
data = data+line;
}
data = data.replace("null", "");
JSONArray JA = new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO = (JSONObject) JA.get(i);
idArray = idArray + JO.get("id") + ",";
amountArray = amountArray + JO.get("amount") + ",";
course_codeArray = course_codeArray + JO.get("course_code") + ",";
courseArray = courseArray + JO.get("course") + ",";
contentArray = contentArray + JO.get("content") + ",";
thumbArray = thumbArray + JO.get("thumb") + ",";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
The data you get from the server are at JSON format but they are not Array . this is an object ,
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}
So you have to loop inside the json object like
for (var key in jsonResponse) {
if (jsonResponse.hasOwnProperty(key)) {
console.log(key + " -> " + jsonResponse[key]);
}
}
EDIT : If you have multiple Objects inside an object you have to loop inside them ( external for) like for(var i in JsonObject)
Your Code is should be like According to your current Response
try{
JSONObject jso = new JSONObject(data);
amountArray =jsonObject.getString("amount");
course_codeArray =jsonObject.getString("yourNextKey");
courseArray = jsonObject.getString("yourNextKey");
contentArray = jsonObject.getString("yourNextKey");
thumbArray = jsonObject.getString("yourNextKey");
}
catch (JSONException e) {
e.printStackTrace();
}

Keep getting java.lang.NegativeArraySizeException: -2, not sure why

I am working on an Android project. I am creating a graph and populating the graph with json content. My problem is that i keep getting this error and i am not sure why. java.lang.NegativeArraySizeException: -2
My Log.v shows the content of the array. So it's not empty. Maybe i am missing something.
I go through the rest api and add everything to the arraylist resModelList.
In the onPostExecute, I want to add my y-axis values to this array list yVals1.
This is where i get my error. (java.lang.NegativeArraySizeException: -2)
If i add the values like this, I get no error.
yVals1 = new ArrayList<Entry>();
yVals1.add(new Entry(1451606400, 10));
yVals1.add(new Entry(1454284800, 20));
yVals1.add(new Entry(1456790400, 30));
yVals1.add(new Entry(1459468800, 50));
My code
Global variables
ArrayList<ResultModel> resModelList;
ArrayList<Entry> yVals1;
Parse Json
//getResult
public class JSONTask extends AsyncTask<String, String, List<ResultModel>> {
#Override
protected List<ResultModel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie",session_name+"="+session_id);
connection.setRequestProperty("X-CSRF-Token", token);
//connection.setRequestProperty("Accept-Encoding", "identity");
connection.connect();
int length = connection.getContentLength();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null){
buffer.append(line);
}
Log.v("TESt", " " + length);
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
resModelList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
ResultModel resModel = new ResultModel();
resModel.setPost_date(finalObject.getString("post_date"));
resModel.setHow_much_has_ocd(finalObject.getString("how_much_has_ocd"));
resModelList.add(resModel);
}
return resModelList;
}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;
}
#Override
protected void onPostExecute(List<ResultModel> result) {
super.onPostExecute(result);
if(!resModelList.isEmpty()){
//here is where i get my errors
yVals1 = new ArrayList<Entry>();
for (ResultModel ocd : resModelList){
int score = Integer.parseInt(ocd.getHow_much_has_ocd());
int timeStamp = Integer.parseInt(ocd.getPost_date());
//I get these log values
Log.v("Score: ", " " + score + " Timestamp: " + timeStamp);
yVals1.add(new Entry(timeStamp, score));
}
graph();
Log.v("Not Empty list", "");
}else {
Log.v("Empty list", "");
}
}
}
finalJson log.v
[{"post_date":"1481895820","did_you_avoid":"25","how_much_has_ocd":"81","how_would_you_rate":"82","overall_how_would":"35","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481723564","did_you_avoid":"13","how_much_has_ocd":"10","how_would_you_rate":"13","overall_how_would":"16","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481723488","did_you_avoid":"28","how_much_has_ocd":"56","how_would_you_rate":"75","overall_how_would":"32","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481537274","did_you_avoid":"53","how_much_has_ocd":"59","how_would_you_rate":"15","overall_how_would":"71","were_there_any_distressing":"1","uid":"2"},{"post_date":"1481295470","did_you_avoid":"67","how_much_has_ocd":"64","how_would_you_rate":"66","overall_how_would":"57","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481097609","did_you_avoid":"72","how_much_has_ocd":"85","how_would_you_rate":"62","overall_how_would":"64","were_there_any_distressing":"0","uid":"2"},{"post_date":"1480673252","did_you_avoid":"33","how_much_has_ocd":"69","how_would_you_rate":"84","overall_how_would":"37","were_there_any_distressing":"1","uid":"2"},
I am a beginner so it might just be simple mistake.
Thanks in advance
I found the error. It was my graph library.
I am using MPAndroidChart library and you need to sort the data. My back-end was sorted desc. I had to change it to Post date (asc).
Its related to this problem.
NegativeArraySizeException adding Scatter Data to a CombinedChart
I hope this helps someone else.

How to read multiple jsonArrays from a file?

I want to read many jsonArrays from a file.
these are the JsonArrays in the file:
[{name:"John",preis:"123",bild:1235},
{name:"Smith",preis:"256",bild:7205},
{name:"Steeven",preis:"632",bild:324035}]
[{name:"Hans",preis:"85",bild:1005},
{name:"Peter",preis:"420",bild:22205},
{name:"Joe",preis:"200",bild:3240}]
[{name:"Jane",preis:"355",bild:10505},
{name:"Calith",preis:"630",bild:96505},
{name:"Eva",preis:"260",bild:32440}]
I can not read the whole file, but i can read only the first jsonArray from the file.
here is my code to read it:
ArrayList<Werkzeug> myWerkzeuge = new ArrayList<Werkzeug>();
String alteBestellung = "";
try {
FileInputStream fileInputStream = openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ( (line = bufferedReader.readLine()) != null){
alteBestellung = alteBestellung + line;
}
JSONArray jsonArray = new JSONArray(alteBestellung);
for (int i = 0; i<jsonArray.length(); ++i){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name_werkzeuge = (String) jsonObject.get("name");
String preis_werkzeuge = (String) jsonObject.get("preis");
Integer bild_werkzeuge = Integer.valueOf( (String)jsonObject.get("bild") );
myWerkzeuge.add( new Werkzeug(name_werkzeuge, preis_werkzeuge, bild_werkzeuge));
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
String bestellung = " ";
for (int i = 0; i< myWerkzeuge.size(); ++i) {
bestellung = bestellung + "\n" + myWerkzeuge.get(i).getName() + " " + myWerkzeuge.get(i).getPreis() + " €" + myWerkzeuge.get(i).getBild();
}
bestellungsTextView.setText( bestellung );
How to read these three jsonArrays from this file?
What you need is a valid json.
You probably want a JsonArray of JsonArray :
[
[{name:"John",preis:"123",bild:1235},
{name:"Smith",preis:"256",bild:7205},
{name:"Steeven",preis:"632",bild:324035}],
[{name:"Hans",preis:"85",bild:1005},
{name:"Peter",preis:"420",bild:22205},
{name:"Joe",preis:"200",bild:3240}],
[{name:"Jane",preis:"355",bild:10505},
{name:"Calith",preis:"630",bild:96505},
{name:"Eva",preis:"260",bild:32440}]
]
This is not valid json .
First of all make a valid json.

XML not parsing completely

I'm trying to extract the xml over Goodread's API, problem is the xml i've extracted is incomplete.
String resultJsonStr = null;
ArrayList<String> results = new ArrayList<String>();
String xml = null;
try {
String str = "https://www.goodreads.com/book/isbn?isbn=9780755380022&key=UpH4L0IYjAXcezlfg0yT2Q";
URL url = new URL(str);
InputStream is = url.openStream();
int ptr = 0;
StringBuilder builder = new StringBuilder();
while ((ptr = is.read()) != -1) {
builder.append((char) ptr);
}
StringBuffer stringBuffer = new StringBuffer(builder);
xml = builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm using this xml
The code stops inside reviews_widget I believe it's reading the thing as a style, and disregarding further lines of the xml.
inside String xml
I'm doing this in preparation for JSON conversion.

Parse string with delimiter ";" (java)

I have a string = "1.515 53.11 612.1 95.1 ; 0 0 0 0"
I'm tring to parse it via this code:
public class SendThread implements Runnable {
public void run()
{
socket = null;
BufferedReader in;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
//Log.d("Connection:", "Trying to connect...");
}
try {
Thread.sleep(30);
} catch (Exception e) {}
}
// Get from the server
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Connection: ", "connected");
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = null;
String[] tempData = null;
String[] windData = null;
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
for (int i = 0; i < currentTemp.length; i++)
currentTemp[i] = (Double) nf.parse(tempData[i]);
for (int i = 0; i < currentWind.length; i++)
currentWind[i] = (Double) nf.parse(windData[i]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currentTemp.length; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
for (int i = 0; i < currentWind.length; i++){
Log.d("Converted data: currentWind["+i+"] = ", currentWind[i]+"");
}
}
socket = null;
Log.d("Connection: ", "lost.");
}
catch (Exception e) {
socket = null;
Log.d("Connection: ", "lost.");
Log.d("Connection:", e+"");
}
}
}
}
Bad code :( But I don't know better way to hold the socket connection :)
I always get "java.text.ParseException: Unparseable number". How to fix it?
tokens, tempData, windData are String[]
Apart from what others said, I bet when you do
windData = tokens[1].split(" ");
you get
windDate = {"","0","0","0","0"}
and try to parse the first element as Number.
Try to do :
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
You don't need to escape the semicolon. Try just doing:
try {
tokens = line.split(";");
tempData = tokens[0].split(" ");
windData = tokens[1].split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
I suspect your parse error is because of the trailing space after the 95.1 in your input string. As it is, your tempData array will have 5 values, the last being ''. Trying to parse that as a number will give you that exception.
Hmm, your code (as posted) does not generate this exception. Secondly, "\\;" is redundant, you can write ";"
You could use, string tokenizer for that.
String s = "1.515 53.11 612.1 95.1 ; 0 0 0 0";
StringTokenizer tokenizer = new StringTokenizer(s,";");
while(tokenizer.hasMoreElements()){
StringTokenizer numberTokenize = new StringTokenizer(tokenizer.nextToken());
while(numberTokenize.hasMoreElements()) {
System.out.println(numberTokenize.nextElement());
}
}
Try using the \s in your split for whitespace; e.g. tempData = tokens[0].split("\s"); ... it represents a whitespace character.

Categories

Resources