跪求 一个Android 读取SD卡里的 json 文件的解析,要完整代码
跪求一个Android读取SD卡里的json文件的解析,要完整代码,一定要读取sd卡的,路径为/storage/extSdCard/123.json在线等,最好是hand...
跪求 一个Android 读取SD卡里的 json 文件的解析,要完整代码,一定要读取sd卡的,路径为 /storage/extSdCard/123.json 在线等,最好是handler.sendMessage(msg)这样handler抛出的
展开
1个回答
展开全部
public class MainActivity extends ActionBarActivity {
private static final String PATH = Environment.getExternalStorageDirectory() + "/123.json";
private android.widget.TextView jsonTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.jsonTv = (TextView) findViewById(R.id.jsonTv);
new Thread() {
@Override
public void run() {
Message msg = handler.obtainMessage();
msg.obj = getFileFromSD(PATH);
msg.what = 1;
handler.sendMessage(msg);
}
}.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
String result = (String) msg.obj;
try {
JSONObject jObj = new JSONObject(result);
jsonTv.setText("name:"+jObj.getString("name")+",age:"+jObj.getInt("age"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
private String getFileFromSD(String path) {
String result = "";
try {
FileInputStream f = new FileInputStream(path);
BufferedReader bis = new BufferedReader(new InputStreamReader(f));
String line = "";
while ((line = bis.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
<RelativeLayout xmlns:android="
xmlns:tools="
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/jsonTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
最后,记得在AndroidMenifest文件中加入权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
123.json的内容
{"name":"rock","age":20}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询