私は解析に関する質問があります(Androidスタジオ)。それは特に何かについてではありません。私のコードは実行されません。エラーはありません。私は、ボタンを押してXMLファイルから解析された特定のテキストを表示できるようにしたい。XMLの簡単な解析
今のところ、私はボタンの一部を省略しますと(アプリ/ srcに/メイン/資産follder。articles.xml)だけ謙虚なのTextViewに
XMLコードを、このテキストを印刷するためにあなたのコードを投げます
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE articles[
<!ELEMENT articles ANY>
<!ELEMENT article ANY>
<!ATTLIST article ID ID #IMPLIED> ]>
<articles>
<article ID="a1">TEST
</article>
<article ID="a2">1.TEST2
</article>
私はテクニックを試していないクラスコード
package com.blah.blah;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
TextView textView;
String stringArticle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager assetManager = this.getAssets();
InputStream inputStream = null;
try {
// Loads your XML file as an InputStream
inputStream = assetManager.open("articles");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element article = doc.getElementById("a1");
String stringArticle = article.getTextContent();
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringArticle);
} catch (IOException e) {
// Exception Handling Code
e.printStackTrace();
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
それはあなたにNodelistを返します。なぜなら、何かを反復したいからです。私はそれが私のプロジェクトにとって役に立たないと思っています。私が欲しいのは、非常に原始的なものです。それらのシンプルな聖書アプリのようなものです。あなたは詩でボタンを押すと、対応するテキストがポップアップします。それは簡単です。
また、エラーはまったくありません。ただ働かない。 TRY部分は実行されないと思います。なぜなら、TextViewにデフォルトの 'hello world'というテキストを与えてくれるからです。しかし、一度私が置いたら、TRY/CATCHブロックの後に
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(stringarticle);
行の後に、私は空のTextViewを取得します。
TY!
['getElementById()']のjavadocを読んだか(https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html#getElementById-java.lang .String-)?あなたがDTDを持っていないので、あなたのXMLには "タイプID"属性がないので、 'getElementById() 'はヌルを返し、次の行に' NullPointerException'を引き起こし、ステートメント "エラーなし"が完全にfalseであることを証明します。あなたは間違いをしているので、おそらくあなたは再び見えるはずです。 – Andreas
私は読んだ、はい。そして、私はそれについて考えさせました。 を <!DOCTYPEの記事[ <!ELEMENT記事ANY> <!ELEMENT記事ANY> <!ATTLISTの記事タイプID #IMPLIED> ]> <記事ID = "1"> blah asdf Nowエラーが表示される:「属性IDはここでは許可されていません」 –
XMLコードを更新しました。私はそれ以上何の問題もないはずだと思う。どうもありがとうございました。それでも私は結果が得られません。マニフェストに宣言する必要があるものがありますか.XML?スキーマのようなもの? –