[Q] Logging data from function - Xposed General

Hey.
I am not entirely sure how to log data from a function.
I am trying to log the accessed URL from the first of the 3 functions in the code pasted below.
I have found the method, but I don't know if It is possible to log the output
Code:
Method - name = HttpConnector.java:
package dk.inlogic.app.res;
private static String getAction(Context context, String action, String version) {
try {
String result = getURLaction(context, action, PreferenceConnector.readString(context, PreferenceConnector.USERNAME, ""), PreferenceConnector.readString(context, PreferenceConnector.PASSWORD, ""), version);
if (result != null) {
return result;
}
} catch (Exception e) {
Log.e("HttpConnector getAction Exception", "action = " + action + ", version = " + version + ", " + e.toString());
}
return "";
}
public static String getTimetable(Context context) {
return getAction(context, "timetable", "2");
}
File 2 - Name, TimetableFragment.java:
package dk.inlogic.app.timetable;
protected String doInBackground(String... args) {
try {
Log.i("TimetableFragment ProgressTask doInBackground", "check for new file");
if (AppInfo.instance().isLive() && HttpConnector.getUpdateNowIfOld("rss2.xml")) {
Log.i("TimetableFragment ProgressTask doInBackground", "Get new file");
saveFile(HttpConnector.getTimetable(this.context));
return "";
} else {
if (!AppInfo.instance().isLive()) {
new DemoDownloadThread(TimetableFragment.this.getActivity()).start();
}
return "";
}
} catch (Exception e) {
Log.e("TimetableFragment doInBackground Exception", e.toString());
}
}

If by "output" you mean result, then you can use param.getResult.
If that's not it, I don't understand what you're trying to do.

Related

[Q] writing txt file

I want to write a text file. But I am not sure how writing down works in Android. Here is my code:
Code:
EditText textbox1 = (EditText) findViewById(R.id.editText);
EditText textbox2 = (EditText) findViewById(R.id.editText2);
EditText textbox3 = (EditText) findViewById(R.id.editText3);
public void writeToPhonebook(View v) {
Button button=(Button) v;
try {
File fajl = new File("phonebook.txt");
Writer writer;
writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fajl, true), "UTF-8"));
writer.append(textbox1.getText() + "\t" + textbox2.getText() + "\t" + textbox3.getText());
writer.write("\r\n");
writer.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
}
catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
can I just leave phonebook.txt or need to put something else? Because with this code apk can't even start on emulator.
OK I done this previus. I now need to load data from text file into table (table layout with 3 columns). Is it possible for application to determine number of needed rows without me adding certain number. Because that data will be changed.
You need permissions to write a file, you set them in the AndroidManifest xml (Every Android Studio project has their own manifest, set it in your project)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then you need to open a file for input/output... You do this in whatever.java
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.util.Log;
public class FileOperations {
public FileOperations() {
}
public Boolean write(String fname, String fcontent){
try {
String fpath = "/sdcard/"+fname+".txt";
File file = new File(fpath);
// If file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();
Log.d("Suceess","Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String read(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fpath));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
}
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Scrollview
Grimspiller said:
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Click to expand...
Click to collapse
1) Yes. Android provide scrollview to scroll on your query.
A. Horizontal scrollview
B. Vertical Scrollview.
Also you can you onTextwatcher() to check if the field size increase , onAfterTextchanged() method you can resize the box is.
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.setVisibility(View.VISIBLE);
}
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
textView.setVisibility(View.GONE);
} else{
textView.setText("You have entered : " + passwordEditText.getText());
}
}
};
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Dynamic Data
Grimspiller said:
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Click to expand...
Click to collapse
hey, As you see on after afterTextChanged(Editable s)
You can again call your table structure code to design it as per size.
I think you should try it once.
Share some amount of code if you find it difficult. I will help you afterTextChanged(Editable s).
I don't need to write text but to read it. Can you look at this code and tell me what is the problem? It can't find the file.
Code:
void showData(){
File fajl = new File("phonebook.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(fajl));
String line;
try {
while ((line = br.readLine()) != null) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
TextView im = new TextView(this);
im.setText(line);
im.setTextColor(Color.BLACK);
im.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
tr.addView(im);
tablel.addView(tr, new TableLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
button2.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
showData();
}
});
I have added to xml TableLayout and one row as header.
I use this for writing to text file:
Code:
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
try {
FileOutputStream fos = openFileOutput("phonebook.txt", Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(textbox1.getText().toString() + "\t" + textbox2.getText().toString() + "\t" + textbox3.getText().toString());
osw.write("\r\n");
osw.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
});
Debbuger says it's writting file and lines just fine. But why I can't read it?
It creates "files" folder inside my app folder. And inside files it is phonebook.txt.

Erroe

i work with this guild: Android Uploading Camera Image, Video to Server with Progress Bar
and when i take image i got this error:
Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/profile_imagephoto.jpg: open failed: ENOENT (No such file or directory
What can i do to fix this?
Code:
//Upload Profile Image
profileImage.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
pictureCheck = "to_profile";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.drawable.ic_action_search);
builder.setMessage("Select What To Do:")
// Positive button functionality
.setPositiveButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(MainActivity.this, "Open Camera...", Toast.LENGTH_SHORT).show();
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, IMAGE_CAPTURE);
}
})
// Negative button functionality
.setNegativeButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(
MainActivity.this, "Open Gallery...", Toast.LENGTH_SHORT).show();
// Do more stuffs
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//dialog.cancel();
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(galleryIntent, RESULT_LOAD_INAGE);
}
});
// Create the Alert Dialog
AlertDialog alertdialog = builder.create();
// Show Alert Dialog
alertdialog.show();
}
});
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
@Override
public void onActivityResult(int requestCodeToProfile, int resultCodeToProfile, Intent dataToProfile) {
super.onActivityResult(requestCodeToProfile, resultCodeToProfile, dataToProfile);
launchUploadActivity(true);
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"profile_image");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ "profile_image" + " directory");
return null;
}
}
// Create a media file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(date.getTime());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
This is a long shot, but the path of your image looks wrong. Are you missing a slash between the last dir and 'photo.jpg'. Should be this line:
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");

Parse Json from URL - Google Finance Quote - PROBLEM

Hi there,
I have an issue with writing my app. I want to obtain the data (as shown below) and get the corresponding value from it. When I run my app on the emulator it crashes when I click the button, precisely on this line:
Code:
JSONObject jsonObject = json.getJSONObject(0);
Can someone at least, please skim through and let me know what I could be doing wrong. It must be something simple, because I am not trying to break into CIA from my phone.
This is a data from the link:
HTML:
// [ { "id": "304466804484872" ,"t" : "GOOG" ,"e" : "NASDAQ" ,"l" : "759.66" ,"l_fix" : "759.66" ,"l_cur" : "759.66" ,"s": "0" ,"ltt":"4:00PM EDT" ,"lt" : "Sep 9, 4:00PM EDT" ,"lt_dts" : "2016-09-09T16:00:03Z" ,"c" : "-15.66" ,"c_fix" : "-15.66" ,"cp" : "-2.02" ,"cp_fix" : "-2.02" ,"ccol" : "chr" ,"pcls_fix" : "775.32" } ]
Here is my class:
Code:
public JSONArray getJson(String url){
// Read response to string
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL Url = new URL(url);
connection = (HttpURLConnection) Url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
is.close();
result = sb.toString();
} catch(Exception e) {
return null;
}
// Convert string to object
try {
String token[] = result.split("//");
JSONArray jarr = new JSONArray (token[1]);
} catch(JSONException e){
return null;
}
return jarr;
}
This is how I use it on a click of a button:
Code:
quotebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Constructing a URL
String urlprefix = "http://finance.google.com/finance/info?client=ig&q=";
String Symbol = editTextSymbol.getText().toString();
String Exchange = editTextExchange.getText().toString();
String url = urlprefix + Exchange + ":" + Symbol;
JSONArray json = getJson(url);
try {
JSONObject jsonObject = json.getJSONObject(0);
String id = jsonObject.getString("id");
EditTextQuoteTime.setText(id);
} catch (JSONException e){
EditTextQuoteTime.setText("ERROR");
}
//try {
// String id = json.getString("id");
// EditTextQuoteTime.setText(id);
//} catch (JSONException e){
// EditTextQuoteTime.setText("ERROR");
// }
}
});
I know I may have asked a question that is widely available online, but most of the posts are from the time before which the libraries were updated and parsing from the URL changed. Most of the posts are slightly different and I feel I am missing something.
I think I have a main problem with decoding the actual JSON string which is shown in the HTML above. I don't know how to omit the first few signs and then get my string from there. Can anyone help, please?

Xml Parsing issue

Hi Folks.
I am new to android studio and object oriented programming in general so apologies if this is obvious but I cannot get my head round it. I have a small xml web server and I can connect to it and send data to it and I can also read it back and view it in the monitor. I want to do xml parsing on it but cannot get it to work.
Below is the xml server being displayed in the android monitor and is from the line "System.out.println(output);"
The response is saved from a string but I think I need it in a different format to do a pull parser on it. The program basically prints this string and then crashes. What is the best way to parse my data? Any help would be really appreciated.
<TITLE>GET test page</TITLE>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: </HEAD>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <BODY>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>LED Control</H1>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?nnn" >ON</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?fff" >OFF</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <IFRAME name=inlineframe style="display:none" >
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: </IFRAME>
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>Status On Now</H1>
05-16 20:19:50.529 13394-14092/com.example.mark.gps_to_server I/System.out: <H2> test</H2>
Click to expand...
Click to collapse
The code:
Code:
public class HTTPRequestTask extends AsyncTask<String , Void, String > {
@Override
protected String doInBackground(String... args) {
String IP = args[0];
System.out.println(IP);
try {
URL url = new URL(IP);
XmlPullParser recievedData = XmlPullParserFactory.newInstance().newPullParser();
recievedData.setInput(url.openStream(),null);
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(output));
System.out.println("doc");
System.out.println(parser);
System.out.println("Disconnecting\n");
conn.disconnect();
//System.out.println(recievedData);
processRecievedData(recievedData);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
private int processRecievedData(XmlPullParser xmlData) {
int recordsFound = 0; // Find values in the XML records
int eventType = -1;
String appId = ""; // Attributes
String itemId = "";
String timeStamp = ""; String data = ""; // Text int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
String tagName = xmlData.getName();
switch (eventType) {
case XmlResourceParser.START_TAG: // Start of a record, so pull values encoded as attributes.
if (tagName.equals("Version")) {
System.out.println("yes");
appId = xmlData.getAttributeValue(null, "Model");
itemId = xmlData.getAttributeValue(null, "vendor_id");
timeStamp = xmlData.getAttributeValue(null, "timestamp");
data = "";
}
System.out.println("no");
break;
// Grab data text (very simple processing)
// NOTE: This could be full XML data to process.
case XmlResourceParser.TEXT:
data += xmlData.getText();
break;
case XmlPullParser.END_TAG:
if (tagName.equals("record")) {
recordsFound++;
//publishProgress(appId, itemId, data, timeStamp);
}
break;
}
//eventType = xmlData.next();
}
// Handle no data available: Publish an empty event.
if (recordsFound == 0) { publishProgress();
}
Log.i(TAG, "Finished processing "+recordsFound+" records.");
return recordsFound;
}
protected void onProgressUpdate(String... values) {
if (values.length == 0) {
Log.i(TAG, "No data downloaded");
}
if (values.length == 4) {
String appId = values[0];
String itemId = values[1];
String data = values[2];
String timeStamp = values[3];
// Log it
Log.i(TAG, "AppID: " + appId + ", Timestamp: " + timeStamp);
Log.i(TAG, " ItemID: " + itemId + ", Data: " + data);
// Pass it to the application handleNewRecord(itemId, data); }
//super.onProgressUpdate(values);
}
}
Thanks.
Probably you should use 3rd party library to parse XML from your web server. This will significantly reduce the code and improve performance. Of course, before parsing xml, you should download the data.
Personal prefference
I prefer the document (DOM) parsing. I think DOM parsing is more object oriented.
Whats the error in the log?
this works for me:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String sb_string = sb.toString();
Document return_doc = null;
if(sb_string.equals(0))
{
}
else {
DocumentBuilder db = null;
try {
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(sb_string));
try {
return_doc = db.parse(is);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Please note! It took me a while before i could get attributes and knew the difference between nodes and elements.
this line of thought will require you to gain more information how to work with documents which might get frustration but in the end it might be beneficial.

Download and parse xml file

Hello, I am learning to program in android and I have the following project. I need to download two XML files from the internet, these files correspond to fuel prices and the location of gas stations. The location and price come in different files, to join these files I need to identify the id of the service station and create a new file with the location and price of the fuel of each station. I am learning how to perform each of these steps. In the code that I add below I want to download a file, save it in memory and display it in TextView. The code does not work correctly, I manage to download the file but I cannot save it in memory to later show it in the Textview. The code downloads the data in the / data / folder, in order to verify that the connection is made and the data is downloaded. How can I download a file and save it in memory to later parse the XML?
Button button=(Button) findViewById(R.id.DownloadBt);
txt = (TextView) findViewById(R.id.txt);
button.setOnClickListener(this);
}
@override
public void onClick(View view){
switch (view.getId()){
case R.id.DownloadBt:
descargarPDF();
break;
}
}
void descargarPDF(){
String urlDescargarPlaces = "https://publicacionexterna.azurewebsites.net/publicaciones/places";
//String urlDescargarPrices = "https://publicacionexterna.azurewebsites.net/publicaciones/prices";
DescargarPDFAsyncTask descargarPlaces=new DescargarPDFAsyncTask("places.xml");
//DescargarPDFAsyncTask descargarPrices=new DescargarPDFAsyncTask("prices.xml");
descargarPlaces.execute(urlDescargarPlaces);
//descargarPrices.execute(urlDescargarPrices);
}
class DescargarPDFAsyncTask extends AsyncTask<String, Integer, String> {
String mFileName;
XMLParse xmlParse=new XMLParse();
DescargarPDFAsyncTask(String fileName){
mFileName=fileName;
}
@override
protected void onPreExecute(){
super.onPreExecute();
}
@override
protected String doInBackground(String... urlFichero) {
String urlADescargar=urlFichero[0];
HttpURLConnection conexion=null;
InputStream input=null;
OutputStream output=null;
try {
URL url = new URL(urlADescargar);
conexion = (HttpURLConnection) url.openConnection();
conexion.connect();
if(conexion.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Connection not successful";
}
input=conexion.getInputStream();
String rutaFicheroGuardado=getFilesDir()+ "/"+mFileName; // /data/data/com.exmaple.downloadurlfile/places.xml.
output=new FileOutputStream(rutaFicheroGuardado);
byte[] data=new byte[1024];
int count=0;
while((count=input.read(data)) >0){//!=-1;
output.write(data,0, count);
}
byteArrayStream = new ByteArrayInputStream(data);//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
} catch (MalformedURLException ex) {
ex.printStackTrace();
return "Error: "+ ex.getMessage();
} catch (IOException ex) {
ex.printStackTrace();
return "Error: "+ex.getMessage();
} finally{
{
try {
if(input!=null) input.close();
if(output!=null) output.close();
if(conexion!=null) conexion.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "Connection successful.";
}
@override
protected void onProgressUpdate(Integer...values){
super.onProgressUpdate(values);
}
@override
protected void onPostExecute(String mensaje){
super.onPostExecute(mensaje);
XMLParse xmlParse= new XMLParse();
xmlParse.parseXML();
Toast.makeText(getApplicationContext(),mensaje,Toast.LENGTH_LONG).show();
}
}
public class XMLParse {
StringBuilder result;
XMLParse(){
}
public void parseXML() {
XmlPullParserFactory parserFactory;
try {
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(byteArrayStream,null);//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
processParsing(parser);
} catch (XmlPullParserException e) {
} catch (IOException e) {
}
}
private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
ArrayList<Player> players = new ArrayList<>();
int eventType = parser.getEventType();
Player currentPlayer = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String eltName = null;
switch (eventType) {
case XmlPullParser.START_TAG:
eltName = parser.getName();
if ("place".equals(eltName)) {
currentPlayer = new Player();
players.add(currentPlayer);
} else if (currentPlayer != null) {
if ("name".equals(eltName)) {
currentPlayer.name = parser.nextText();
} else if ("cre_id".equals(eltName)) {
currentPlayer.cre_id = parser.nextText();
} else if ("x".equals(eltName)) {
currentPlayer.x = parser.nextText();
} else if("y".equals(eltName)){
currentPlayer.y = parser.nextText();
}
}
break;
}
eventType = parser.next();
}
printPlayers(players);
}
private void printPlayers(ArrayList<Player> players) {
StringBuilder builder = new StringBuilder();
for (Player player : players) {
builder.append(player.name).append("\n").
append(player.cre_id).append("\n").
append(player.x).append("\n").
append(player.y).append("\n\n");
}
txt.setText(builder.toString());
}
}
}

Categories

Resources