gpt4 book ai didi

java - Android studio,ArrayList 无法正确显示 ListView 中的项目

转载 作者:行者123 更新时间:2023-12-01 08:51:30 25 4
gpt4 key购买 nike

我有一个微调器,我可以从中选择数据进入数组列表,该数组列表与 ListView 一起使用来显示内容。我知道这些值将进入 Arraylist,但是当涉及到 ListView 时,它无法正常工作。

发生的情况是第一个项目会正常加载,但是当我添加另一个项目时,前一个项目会消失,而新项目会显示在前一个项目的下一个位置,这对于我添加的每个项目都会重复。

创建行程代码:

public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

TextView txtDate;

private Spinner spinnerAttraction;
private Spinner spinnerTransport;
private boolean saved;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ProgressDialog pDialog;
private List<String> lables = new ArrayList<String>();

private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;

private LayoutInflater myInflator;
private View myView;

private DBManager db;
private myAdapter adapter;

private int ID;
private String NAME;
private String LOCATION;
private String TIME;

static final int DIALOG_ID = 0;
int hour_x;
int min_x;
private ListView ls;
private TextView TextTime;
private String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);

saved = false;

ls = (ListView)findViewById(R.id.listCreateItinerary);

myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);

db = new DBManager(this);

categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);

new GetAttractions().execute();

showTimePickerDialog();

Bundle bundle = getIntent().getExtras();

ItineraryName = bundle.getString("Itinerary Name");

(this).registerForContextMenu(ls);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.listCreateItinerary){
this.getMenuInflater().inflate(R.menu.context_menu,menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuDelete:

return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, 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 (saved == false) {
if (id == R.id.go_home) {
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
}
else if(saved == true){
if (id == R.id.go_home) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}

public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}

public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}

public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}

public void addTransportToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}

public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}

}

public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
saved = true;
}

public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
showDialog(DIALOG_ID);

}
});
}

@Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}

protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(ID,NAME,LOCATION,TIME));

}
};

public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();

NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}

/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
System.out.println(categoriesList.get(i));
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}

/**
* Async task to get all attraction categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");

for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
// new GetTransport().execute();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);

Log.e("Response: ", "> " + json);

if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");

for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}

} catch (JSONException e) {
e.printStackTrace();
}

} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}

}

class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;

public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}

@Override
public int getCount() {
return listItem.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View view, ViewGroup viewGroup) {

ac = listItem.get(position);

TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);

TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
return myView;
}
public void deleteItineraryItem(){
Entities.remove(ID);
finalEntities.remove(ID);
loadAttractions();
}
}
}

public void loadAttractions(){...,是更新 ListView 的方法代码,上面的两个方法与单独的按钮相关,并将微调项目添加到数组列表(实体)中,谢谢大家谁能帮助我。

最佳答案

而不是:

@Override
public Object getItem(int position) {
return null;
}

试试这个代码:

 @Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position); //return list item
}

关于java - Android studio,ArrayList 无法正确显示 ListView 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42371864/

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