我在从JSON .txt文件中提取信息并将该信息显示到ListFragment
时遇到了一些困难。
我在资源文件夹中保存.txt文件,其类型为:
{
"cities":
[
{
"name":"NAME",
"state":"STATE",
"latitude":45.000000,
"longitude":-102.089016,
},
{
"name":"NAME",
"state":"STATE",
"latitude":35.000000,
"longitude":-102.089016,
},
...
{
"name":"NAME",
"state":"STATE",
"latitude":15.000000,
"longitude":-102.089016,
}
]
}
我正在为以下城市使用公共课:public class City implements Serializable {...}
其中包含每个字段的getter和setter。
我正在尝试使用扩展LoadDataAsyncTask
的类AsyncTask<>
加载数据:
我认为为了将这些数据加载到ListFragment,我需要在doInBackground()
方法中对其进行编码:
@Override
protected Void doInBackground(String... arg0) {
AssetManager manager = contexto.getAssets();
JSONArray jarray = null;
StringBuilder builder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader( new InputStreamReader( manager.open("jsonfile.txt") ) );
String line;
JSONObject jobject = new JSONObject();
// Read data
while((line = reader.readLine()) != null) {
builder.append(line);
String city = jobject.getString("name");
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.e("", e.toString());
}
return null;
}
然后有一个类CitiesListFragment包含这样的代码:
public class CitiesListFragment extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<City> adapt = new ArrayAdapter<City>(getActivity(),
android.R.layout.simple_list_item_1, new ArrayList<City>());
LoadDataAsyncTask task = new LoadDataAsyncTask(getActivity(), adapt);
tarea.execute("jsonfile.txt");
setListAdapter(adaptador);
}
}
我想我错过了一些编码,但我不确定在哪里编写它。
答案 0 :(得分:0)
您应该在jsonlint.com上查看您的json响应。将json粘贴到那里,看看json的格式是否有效。
如果有效则使用此方法并获得完整的jsonString响应。
private String readJson() {
String jsonResponse = null;
try {
InputStream inputStream = context.getResources().openRawResource(R.raw.json);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder strBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
strBuilder.append(receiveString);
}
inputStream.close();
jsonResponse = strBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
}
catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return jsonResponse;
}
一旦你有了jsonReponse,只需使用gson或任何其他方法来解析它。
答案 1 :(得分:0)
第一:这是我对你的json做的事情:
{
"cities":[
{
"name":"NAME",
"state":"STATE",
"latitude":"45.000000",
"longitude":"-102.089016"
},
{
"name":"NAME",
"state":"STATE",
"latitude":"35.000000",
"longitude":"-102.089016"
},
{
"name":"NAME",
"state":"STATE",
"latitude":"15.000000",
"longitude":"-102.089016"
},
]
}
我将它保存为资源文件夹中的JSON(yourjson.json),以下是我访问它的方式:
首先:只使用活动而不是ListActivity ..您可以在您的情况下使用ListActivity。
public class CitiesListFragment extends Activity {
ArrayList<String> QuestionForSliderMenu = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> STATE = new ArrayList<String>();
ArrayList<String> LATITUDE = new ArrayList<String>();
ArrayList<String> LONGITUDE = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.citieslayout);
ListView listView = (ListView) findViewById(R.id.listview1);
MyAdapter adapter = new MyAdapter(this, QuestionForSliderMenu);
listView.setAdapter(adapter);
try {
ParsedData();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ParsedData() {
NAME = new ArrayList<String>();
STATE = new ArrayList<String>();
LATITUDE = new ArrayList<String>();
LONGITUDE = new ArrayList<String>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray array = json.getJSONArray("cities");
QuestionForSliderMenu = new ArrayList<String>();
Log.d("Cities: ", array.toString());
for (int my = 0; my <= array.length(); my++) {
JSONObject c = array.getJSONObject(my);
String name = c.getString("name");
String state = c.getString("state");
String latitude = c.getString("latitude");
String longitude = c.getString("longitude");
NAME.add(name);
STATE.add(state);
LATITUDE.add(latitude);
LONGITUDE.add(longitude);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private class MyAdapter extends BaseAdapter {
private int lastPosition = -1;
private Context context;
private ArrayList<ModelClass> name;
private ArrayList<ModelClass> state;
private ArrayList<ModelClass> latitude;
private ArrayList<ModelClass> longitude;
private ArrayList<ModelClass> MainItems;
private ArrayList<String> mainList;
public MyAdapter(Context context, ArrayList<ModelClass> name,
ArrayList<ModelClass> state, ArrayList<ModelClass> latitude,
ArrayList<ModelClass> longitude) {
super();
this.context = context;
this.name = name;
this.state = state;
this.latitude = latitude;
this.longitude = longitude;
}
public MyAdapter(Context applicationContext,
ArrayList<String> questionForSliderMenu1) {
super();
this.mainList = questionForSliderMenu1;
}
@Override
public int getCount() {
return STATE.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cities_row, null);
}
TextView name = (TextView) convertView.findViewById(R.id.Name);
TextView state = (TextView) convertView.findViewById(R.id.State);
TextView latitude = (TextView) convertView
.findViewById(R.id.Latitude);
TextView longitude = (TextView) convertView
.findViewById(R.id.Longitude);
try {
name.setText(NAME.get(position));
state.setText(STATE.get(position));
latitude.setText(LATITUDE.get(position));
longitude.setText(LONGITUDE.get(position));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
}
//这是我从资源获取json的地方,在上面的方法中只使用此方法获取json对象。
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getApplicationContext().getAssets().open(
"yourjson.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
这就是全部。最后,布局:
cities_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cities"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/State"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="States"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/Latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/Longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
并且,citieslayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listview1"
android:layout_width="match_parent"
android:layout_height="338dp"
android:layout_weight="0.36"
android:background="#333333">
</ListView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
希望这会有所帮助.. :)