我正在尝试使用来自JSON API的数据创建一个非常简单的列表视图。我对Android很新,并且遇到了许多非常不同且复杂的解决方案,这些解决方案对我不起作用。这是JSON数据的示例,我希望列出名称,并在单击每个名称时显示它们,它显示一个显示其余值的页面。
{
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"image": "https://loremflickr.com/320/240?lock=1"
},
{
"name": "C-3PO",
"height": "167",
"mass": "75",
"hair_color": "n/a",
"skin_color": "gold",
"eye_color": "yellow",
"birth_year": "112BBY",
"gender": "n/a",
"image": "https://loremflickr.com/320/240?lock=2"
},
}
这是我的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ListView myListView = (ListView) findViewById(R.id.listView1);
try
{
**// String jsonInput = "[\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\"]";
JSONObject jsonInput;
jsonInput = new JSONObject("http://public.duethealth.com/api/project.json");
JSONArray jsonArray = new JSONArray(jsonInput);
int length = jsonArray.length();
List<String> listContents = new ArrayList<String>(length);
for (int i = 0; i < length; i++)
{
listContents.add(jsonArray.getString(i));
}
myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents));
}
catch (Exception e)
{
e.setStackTrace();
}**
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我的代码在onCreate()中,当我将JSON读作字符串(注释掉的行)时,它似乎有效。
我似乎不明白如何从URL读取JSON对象,然后从该Object读取数组,然后将该数组中的每个对象打印到我的listview中。我理解它背后的逻辑,但是我对android尝试编码它是如此陌生,这让我很难受。我已经看过很长的解析方法和东西,但似乎解决方案应该像单行一样简单(只需从url读取)。谁能看到我的问题在哪里?
谢谢!