- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在使用一个类将所有 json 数据添加到 bookList HashMap 数组列表中。现在我需要 MainActivity 上的列表根据引入的数据进行更新。
这似乎是基于我的选择,它正在将所有正确的数据记录到 logcat 中,但 ListView 或结果 View 中没有显示任何内容......我假设我必须返回 bookList HashMap arraylist 返回到 MainActivity 以便以某种方式使用...
MainActivity.java
public class MainActivity extends Activity {
ArrayList<HashMap<String, String>> bookList;
Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_form);
context = this;
list = (ListView) findViewById(R.id.game_list);
// Possibly this is reading the wrong bookList, so it's not showing the ListView???
ListAdapter adapter = new SimpleAdapter(context,
bookList, R.layout.list_view, new String[] {
TAG_TITLE, TAG_INFO }, new int[] {
R.id.title, R.id.info });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
resultsView.setBackgroundColor(Color.DKGRAY);
resultsView.setText("Book: "
+ bookList.get(+position).get(TAG_TITLE)
+ "\n"
+ "About Book: "
+ bookList.get(+position).get(TAG_INFO));
}
});
}
}
Json.java
public class Json {
String TAG_PARENT = "results";
String TAG_TITLE = "title";
String TAG_INFO = "info";
public static ArrayList<HashMap<String, String>> bookList = new ArrayList<HashMap<String, String>>();
public static void pSearch(String item) {
String origURL = item;
URL resultURL;
try {
resultURL = new URL(origURL);
Json json = new Json();
Json.SnagData gd = json.new SnagData();
gd.execute(resultURL);
} catch (MalformedURLException e) {
Log.e("INCORRECT URL", "CHECK URL PASSED");
resultURL = null;
}
}
public class SnagData extends AsyncTask<URL, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
bookList.clear();
}
@Override
protected String doInBackground(URL... urls) {
String fURL = "";
for (URL url : urls) {
fURL = NetworkConnection.getURLResponse(url);
}
return fURL;
}
protected void onPostExecute(String result) {
try {
JSONObject json = new JSONObject(result);
JSONArray results = json.getJSONArray(TAG_PARENT);
int j = results.length();
for (int i = 0; i < j; i++) {
JSONObject jo = results.getJSONObject(i);
String title = jo.getString(TAG_TITLE);
String info = jo.getString(TAG_INFO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_INFO, info);
bookList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
最佳答案
使用接口(interface)作为回调
编辑:
public class SnagData extends AsyncTask<URL, Void, String> {
String TAG_PARENT = "results";
String TAG_TITLE = "title";
String TAG_INFO = "info";
public interface returnListListener
{
public void returnList(ArrayList<HashMap<String,String>> list);
}
returnListListener mCallback;
public SnagData(Context context)
{
mCallback = (returnListListener)context;
}
ArrayList<HashMap<String,String>> booklist = new ArrayList<HashMap<String,String>>();
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(URL... urls) {
String fURL = "";
for (URL url : urls) {
fURL = NetworkConnection.getURLResponse(url);
}
return fURL;
}
protected void onPostExecute(String result) {
try {
JSONObject json = new JSONObject(result);
JSONArray results = json.getJSONArray(TAG_PARENT);
int j = results.length();
for (int i = 0; i < j; i++) {
JSONObject jo = results.getJSONObject(i);
String title = jo.getString(TAG_TITLE);
String info = jo.getString(TAG_INFO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_INFO, info);
bookList.add(map);
if(mCallback!=null)
{
mCallback.returnList(booklist);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Activity 中
public class MainActivity extends Activity implements returnListListener
{
ListView list;
URl url; /// initialize your url
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_form);
new SnagData(MainActivity.this).execute(url); // url passed to doInbackgrounf
list = (ListView) findViewById(R.id.game_list);
}
public void returnList(ArrayList<HashMap<String,String>> list)
{
// set adapter with list here
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
list, R.layout.list_view, new String[] {
TAG_TITLE, TAG_INFO }, new int[] {
R.id.title, R.id.info });
list.setAdapter(adapter);
}
}
编辑2:
前往评论中的链接 ( https://github.com/woolardjason/JavaTest )
public class MainActivity extends Activity implements returnListListener {
// Local Variables
Context context;
String mTAG = "NETWORK ACTIVITY - MainActivity Class";
String mUrlString = "http://www.giantbomb.com/api/games/?api_key=84bb1f7ad08b299e6c29992eff7ed6278f406a15&format=json&limit=5&sort=original_release_date:asc&filter=expected_release_year:";
String[] mReleaseYears;
public static TextView resultsView;
ListView mList;
TextView name;
TextView deck;
TextView release;
Boolean mConnected = false;
ArrayList<HashMap<String, String>> gameList;
// Node names from JSON Data
String TAG_PARENT = "results";
String TAG_NAME = "name";
String TAG_DECK = "deck";
String TAG_RELEASE = "expected_release_year";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_form);
// Setting context local var to this activity.
context = this;
resultsView = (TextView) findViewById(R.id.results_view);
// Setting mReleaseYears Local Var to String Array from resources
mReleaseYears = getResources().getStringArray(R.array.yearArray);
mList = (ListView) findViewById(R.id.game_list);
// Creating Spinner Adapter
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, mReleaseYears);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Creating the spinner
Spinner viewSpinner = (Spinner) findViewById(R.id.release_years);
// Setting the spinners adapter to created adapter 'spinnerAdapter'
viewSpinner.setAdapter(spinnerAdapter);
// Setting
viewSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// Setting Local Var Boolean 'mConnected' to the current
// context's status
mConnected = NetworkConn.grabConnectionStatus(context);
// If connected...
if (mConnected) {
// Performing a search using performSearch method based off
// current selected spinner position. Passes is data from
// array (mReleaseYears) based on selection to allow user
// manipulation of data.
//Data.performSearch(mUrlString + mReleaseYears[position]);
new Data(MainActivity.this).execute(mUrlString+ mReleaseYears[position]);
// If not connected...
} else {
// Setting the result's view text
resultsView.setText(R.string.networkError);
AlertDialog.Builder adb = new AlertDialog.Builder(context);
adb.setMessage(R.string.networkError);
adb.setCancelable(true);
adb.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog errorAlert = adb.create();
errorAlert.show();
}
}
// Method onNothingSelected...self explanatory method not utilized
// at the moment.
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// Setting list's item click listener
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void returnList(final ArrayList<HashMap<String, String>> list) {
// TODO Auto-generated method stub
// set adapter with list here
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
list, R.layout.list_view, new String[] {
TAG_NAME, TAG_RELEASE }, new int[] {
R.id.name, R.id.release });
mList.setAdapter(adapter);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
// Method to be called upon item click within list
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// Setting the resultsView background color to dark
// gray (in case an error occurs, and it's currently
// red)
resultsView.setBackgroundColor(Color.DKGRAY);
// Setting the resultView to display the current
// position's (in list) item details based off
// pulled in json data thats stored in gameList
resultsView.setText("Game: "
+ list.get(+position).get(TAG_NAME)
+ "\n"
+ "About Game: "
+ list.get(+position).get(TAG_DECK)
+ "\n"
+ "Release Year: "
+ list.get(+position).get(TAG_RELEASE));
}
});
}
}
数据
public class Data extends AsyncTask<String, Void, String> {
// Node names from JSON Data
String TAG_PARENT = "results";
String TAG_NAME = "name";
String TAG_DECK = "deck";
String TAG_RELEASE = "expected_release_year";
static Context context;
public static ArrayList<HashMap<String, String>> gameList = new ArrayList<HashMap<String, String>>();
public interface returnListListener
{
public void returnList(ArrayList<HashMap<String,String>> list);
}
returnListListener mCallBack;
public Data(Context context)
{
mCallBack = (returnListListener)context;
}
// onPreExecute Method - Setting TextView Cars to TextView IDS located
// in xml
protected void onPreExecute() {
super.onPreExecute();
// Clearing out the GameList (for reloads)
gameList.clear();
}
@Override
protected String doInBackground(String... urls) {
// Resetting URL
String fURL = "";
//for (URL url : urls) {
// Setting fURL stringVar to response of getURLReponse method
// from WebClass class.
fURL = NetworkConn.getURLResponse(urls[0]);
//}
// Returning fURL string var
return fURL;
}
// OnPostExecute method
protected void onPostExecute(String result) {
try {
// Setting json var for type JSONObject to new JSOBObject with
// passed in string result
JSONObject json = new JSONObject(result);
// Setting results JSONArray var to results json node
JSONArray results = json.getJSONArray(TAG_PARENT);
// Setting j int var to results array length
int j = results.length();
// For conditional cycling through results array grabbing
// defined nodes and storing them
for (int i = 0; i < j; i++) {
// Setting JSONObject var 'jo' to each object within results
// array
JSONObject jo = results.getJSONObject(i);
// Storing pulled in JSON Nodes into separate strings
String nam = jo.getString(TAG_NAME);
String dec = jo.getString(TAG_DECK);
String rel = jo.getString(TAG_RELEASE);
// Creating HashMap entitled map and initializing it
HashMap<String, String> map = new HashMap<String, String>();
// Putting JSON nodes into map
map.put(TAG_RELEASE, rel);
map.put(TAG_NAME, nam);
map.put(TAG_DECK, dec);
// Adding data to gameList Local var
gameList.add(map);
if(mCallBack!=null)
{
mCallBack.returnList(gameList);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
网络连接
public class NetworkConn {
static Boolean isConnected = false;
static String mTAG = "NETWORK ACTIVITY - Webclass Class";
public static Boolean grabConnectionStatus(Context context){
checkConnectionStatus(context);
return isConnected;
}
// checkConnectionStatus method
public static void checkConnectionStatus(Context context) {
// Obtaining context system service /Connectivity_Service
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// Obtaining active network info for created connectivitymanager instance
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// checking if networkInfo is null or not
if (networkInfo != null) {
// checking if network info is connected
if (networkInfo.isConnected()) {
// logging connection type if connected, and networkInfo is not null
Log.i(mTAG, "connection type: " + networkInfo.getTypeName());
// setting isConnected to true if connected and networkInfo is not null
isConnected = true;
}
}
}
// getURLResponse method
public static String getURLResponse(String url) {
// Resetting response var by setting it to equal nothing.
String response = "";
try {
// Initializing URLConnection
URL url1 = new URL(url);
URLConnection connection = url1.openConnection();
// Setting created bufferedinputstring to connection input stream
BufferedInputStream bis = new BufferedInputStream(
connection.getInputStream());
// Setting contextByte
byte[] contextByte = new byte[1024];
// Setting int bytesRead
int bytesRead = 0;
// Setting StringBuffer entitled responseBuffer to new StringBuffer
StringBuffer responseBuffer = new StringBuffer();
// While conditional to check while bytesRead is
while ((bytesRead = bis.read(contextByte)) != -1) {
response = new String(contextByte, 0, bytesRead);
responseBuffer.append(response);
}
response = responseBuffer.toString();
Log.i(mTAG, response);
} catch (IOException e) {
response = "Something happened, no info returned!";
Log.e(mTAG, "Something happened, no info returned!", e);
}
return response;
}
}
快照
关于java - 使用类中生成的 Hashmap ArrayList 数据在 MainActivity 的 ListView 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686653/
我有不同的结构,它们都包含一个 HashMap与 String作为键,但具有不同的值类型。例如,一个结构有一个类型为 HashMap 的成员, 另一个将有一个 HashMap 类型的成员, 等等。 我
我想制作一个包含学生姓名和科目的板,每个学生在每个科目中都有一个成绩(或者没有..他可以离开考试而不写,然后他的案子将是空的)。我只想使用 HashMap。我的意思是,它会是这样的: HashMap>
是否有内存和速度高效的方法来在 HashMap 中动态存储唯一键:值对? key 保证是唯一的,但它们的数量经常变化。插入和删除必须很快。 我所做的是包含有符号距离场的八叉树(非线性/完整)。八叉树经
有谁知道为什么选择通过 LinkedList 而不是另一个 Hashmap 来实现 HashMap 的存储桶。如果桶本身变成了 HashMap,那么 contains 或 get 的时间复杂度似乎是
我想创建一个具有嵌套结构的 HashMap,就像这个复杂的示例: { type: boy name: Phineas father: type: man
这个问题在这里已经有了答案: How do I create a global, mutable singleton? (7 个答案) 关闭 7 年前。 我想要一个可扩展的字典,将 Object 与
HashMap> hm = new HashMap>(); hm.put("Title1","Key1"); for(int i=0;i hm1 = new H
我必须修改当前代码以适应 Spring MVC。我有 HashMap hashmap = new HashMap(); request.setAttribute("dslrErrors", hashm
我正在尝试进行一些错误捕获。 错误应该检查数组的长度是否小于 2,并检查 HashMap 是否包含用户输入的键。 捕获的错误必须仅使用 if 语句,并且必须使用 .length() 方法,并且必须使用
在 stackoverflow 上提出另一个问题后,(Java- Why this program not throwing concurrent Modification exception)我开始
我有两个类,想使用 org.dozer.Mapper( http://dozer.sourceforge.net/ ) 将 Female 对象的属性映射到 Male 对象。 第一类是: public
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be
是否有任何方法可以检查 HashMap 是否包含一组特定的键(这些键是在数组中给出的)。当我尝试类似下面的代码时,它返回 false。 map.containsKey(arrayOf("2018-01
跟进我的问题:How To Access hash maps key when the key is an object 我想尝试这样的事情:webSearchHash.put(xfile.getPa
我有一个可扩展的 ListView ,对于每个 child ,我需要有 4 个“额外”或字符串或其他名称来调用它:- 子标题- 描述- 链接1- 链接2 跟着教程,创建 ListView 、不同的 p
我想确保这是正确的,因为如果不正确,它可能会破坏我的应用程序。 我有这个: private static HashMap> balance = new HashMap<>(); 如果我得到这样的值:
我想做以下事情: 为某个键查找Vec,并将其存储以备后用。 如果它不存在,则为键创建一个空的 Vec,但仍将其保存在变量中。 如何有效地做到这一点?自然地,我认为我可以使用 match: use st
我想做以下事情: 为某个键查找Vec,并将其存储以备后用。 如果它不存在,则为键创建一个空的 Vec,但仍将其保存在变量中。 如何有效地做到这一点?自然地,我认为我可以使用 match: use st
我想做以下事情: 为某个键查找Vec,并将其存储以备后用。 如果它不存在,则为键创建一个空的 Vec,但仍将其保存在变量中。 如何有效地做到这一点?自然地,我认为我可以使用 match: use st
我想做以下事情: 为某个键查找Vec,并将其存储以备后用。 如果它不存在,则为键创建一个空的 Vec,但仍将其保存在变量中。 如何有效地做到这一点?自然地,我认为我可以使用 match: use st
我是一名优秀的程序员,十分优秀!