gpt4 book ai didi

java - 使用类中生成的 Hashmap ArrayList 数据在 MainActivity 的 ListView 中使用?

转载 作者:太空宇宙 更新时间:2023-11-04 15:18:13 25 4
gpt4 key购买 nike

我正在使用一个类将所有 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;
}
}

快照

enter image description here

关于java - 使用类中生成的 Hashmap ArrayList 数据在 MainActivity 的 ListView 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com