android的ListView如何追加数据?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android的ListView如何追加数据?相关的知识,希望对你有一定的参考价值。

刚开始绑定10条,后面点击更多应该把新的10条追加进去,而不是重新绑定20条。

实现代码如下:  

package com.app.test01;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.adapter.MyWeixinJSON;
import com.app.adapter.MyWeixinList;

/**
* 点击  追加数据的ListView
* @author 402-9
*
*/
public class ListViewPage extends Activity
 private ListView lv;
 private BaseAdapter mJson;
 private JSONArray mData = new JSONArray();// JSON数据源
 private View view_page_footer;// 底部视图
 private int num = 1;// 加载数据计数
 private int count = 50;// 总数据

 
// private boolean flag;
 @Override
 protected void onCreate(Bundle savedInstanceState)
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.weixin);
   lv = (ListView) findViewById(R.id.lv);
   getJSONArray(mData);
   
   mJson = new MyWeixinJSON(mData, this);

   view_page_footer = LayoutInflater.from(this).inflate(
       R.layout.view_page_footer, null);
   lv.addFooterView(view_page_footer);// 添加底部视图
   TextView text_page = (TextView) view_page_footer.findViewById(R.id.text_page);
   text_page.setOnClickListener(new View.OnClickListener()
     // 点击按钮 追加数据 并通知适配器
     @Override
     public void onClick(View v)
       // TODO Auto-generated method stub
       TextView tv = (TextView) v;
       tv.setText("正在加载中...");
       getJSONArray(mData);
       tv.setText("下一页");
       mJson.notifyDataSetChanged();
     
   );

   lv.setAdapter(mJson);// 绑定适配器

 

 /** 数据源JSONArray */
 private void getJSONArray(JSONArray jArray)
   try
     for (int i = 1; i <= 5; i++)
       JSONObject jsonObject = new JSONObject();
       jsonObject.put("title", "姓名" + num++);
       jsonObject.put("time", "9月29日");
       jsonObject.put("info", "我通过了你的好友验证请求,现在我们可以开始对话啦");
       jsonObject.put("img", R.drawable.special_spring_head2);
       jArray.put(jsonObject);
       if (num == count)
         lv.removeFooterView(view_page_footer);
         Toast.makeText(this, "没有更多数据了...", Toast.LENGTH_LONG)
             .show();
       
     
    catch (Exception e)
     // TODO: handle exception
   
 
 

   

   其中,所添加的底部视图,只有一个供点击追加的按钮:
 

 
   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_
   android:layout_
   android:orientation="vertical"
   android:padding="5dp">

   <TextView
       android:id="@+id/text_page"
       android:layout_
       android:layout_
       android:text="下一页"
    android:gravity="center"/>

</LinearLayout>

其中,所添加的底部视图,只有一个供点击追加的按钮:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical" 
    android:padding="5dp">

    <TextView
        android:id="@+id/text_page"
        android:layout_
        android:layout_
        android:text="下一页" 
     android:gravity="center"/>

</LinearLayout>

效果图

点击“下一页”,在ListView后追加数据。

追加完成后,清除底部视图。

参考技术A listview的适配器adapter里面调用additem(List)这样的方法,如果没有,就自己 写一个,就是给adapter中的list追加数据而已,然后调用adapter的刷新就好了,esay 参考技术B 把你置入适配器的list追加10条,再使用适配器的notifyDataSetChanged()刷新本回答被提问者采纳 参考技术C 三十岁

Android ListView清除

我有一个ListView。我想动态更改ListView的内容。我使用适配器将值传递给它。当我传递它接受并显示的值时,但当我按下后退按钮并传递新数据时,它仍会显示旧数据和新数据。

我试过了

arraylist.clear(),adapter_object.notifyDataSetChanged(); ,listview.setAdapter(null);

但这些都没有奏效。

这是我如何将值传递给getter和setter类

  for (int i = 0; i <FlightTboSearch.flight_name_jeet.size(); i++) 
            flight_one_way_detail.add(new Flight_info_details(FlightTboSearch.flight_name_jeet.get(i).toString(), FlightTboSearch.flight_departure_jeet.get(i), FlightTboSearch.flight_arrival_jeet.get(i), FlightTboSearch.flight_name_jeet.get(i).toString()));

            flight_one_way_adapter = new Flight_info_adapter(View_fligh_info.this, flight_one_way_detail);

        

这是适配器代码

public class Flight_info_adapter extends BaseAdapter 
Context context;


public static ArrayList<Flight_info_details> rowItems;

Flight_info_adapter(Context context, ArrayList<Flight_info_details> rowItems) 

    this.context = context;
    this.rowItems = rowItems;


@Override
public int getCount() 
    return rowItems.size();


@Override
public Object getItem(int position) 
    return rowItems.get(position);


@Override
public long getItemId(int position)

    return rowItems.indexOf(getItem(position));


/* private view holder class */
private class ViewHolder 
    TextView flight;
    TextView departur;
    TextView arrival;
    ImageView img_logo;


@Override
public View getView(int position, View convertView, ViewGroup parent)

    final ViewHolder holder;
    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) 
        convertView = mInflater.inflate(R.layout.flight_row, null);
        holder = new ViewHolder();
    
    else
    
        holder = (ViewHolder) convertView.getTag();
    
    holder.flight = (TextView) convertView.findViewById(R.id.flight);
    holder.departur = (TextView) convertView.findViewById(R.id.departure);
    holder.arrival = (TextView) convertView.findViewById(R.id.arrival);
    holder.img_logo = (ImageView) convertView.findViewById(R.id.img_logo);
    try
    
        final Flight_info_details row_pos = rowItems.get(position);
        String flight = String.valueOf(row_pos.getflight());
        String departur=String.valueOf(row_pos.getdeparture());
        String arrival=String.valueOf(row_pos.getarrival());
        String flight_name=String.valueOf(row_pos.getflight_name());

        if(flight_name.equals("SpiceJet"))
        

            holder.img_logo.setImageBitmap(View_fligh_info.spicejet);
        else if(flight_name.equals("Indigo"))
        
            holder.img_logo.setImageBitmap(View_fligh_info.indigo);
        else if(flight_name.equals("Jet Airways"))
        
            Log.e("confirmation_Adapter-",flight_name);
            holder.img_logo.setImageBitmap(View_fligh_info.jetairways);
        else if(flight_name.equals("Air India"))
        
            holder.img_logo.setImageBitmap(View_fligh_info.ai);
        else if(flight_name.equals("Klm Uk"))
        
            holder.img_logo.setImageBitmap(View_fligh_info.uk);
        else if(flight_name.equals("Air Asia"))
        
            holder.img_logo.setImageBitmap(View_fligh_info.airasia);
        
        holder.flight.setText(flight);
        holder.departur.setText(departur);
        holder.arrival.setText(arrival);
    
    catch (Exception e)
    
        Log.e("PASS_ADAP ERROR:", e.getMessage());
    
    convertView.setTag(holder);
    return convertView;


这是getter setter类

public class Flight_info_details 

String flight;
String departure;
String arrival;
String flight_name;





public String getflight()return flight;
public void setflight() 
    this.flight = flight;


public String getdeparture() return departure;
public void setdeparture() this.departure = departure;

public String getarrival() return arrival;
public void setarrival() this.arrival = arrival;

public String getflight_name() return flight_name;
public void setflight_name() this.flight_name = flight_name;

public Flight_info_details(String flight, String departure, String arrival, String flight_name)


    this.flight = flight;
    this.departure=departure;
    this.arrival=arrival;
    this.flight_name=flight_name;




我哪里错了

EDIT-1 ACTIVITY设置值

public class View_fligh_info extends AppCompatActivity

ArrayList<ViewFlightDetails> newUsers;

public static Bitmap spicejet,indigo,ai,uk,SaudiArabianAirlines,EthiopianAirlinesSC,KenyaAirways,ThaiAirwaysInternational,jetairways,airasia,HahnAirSystems,TurkishAirlines,AirMauritius,EmiratesAirlines,OmanAviation,SriLankanAirlines,Alitalia,EtihadAirways,AirFacilities,GulfAir;

TextView return_text;
Button next;
LinearLayout retur_text_2;
ListView flight_information,return_list;

public static ArrayList<Flight_info_details> flight_one_way_detail;
public static Flight_info_adapter flight_one_way_adapter;

protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    setContentView(R.layout.view_flight_info);
    return_text=(TextView)findViewById(R.id.return_text);


    next=(Button)findViewById(R.id.next);

    flight_information = (ListView) findViewById(R.id.list_oneway);

    spicejet = BitmapFactory.decodeResource(this.getResources(),R.drawable.spice);
    indigo = BitmapFactory.decodeResource(this.getResources(),R.drawable.indigo);
    ai = BitmapFactory.decodeResource(this.getResources(),R.drawable.ai);
    uk = BitmapFactory.decodeResource(this.getResources(),R.drawable.uk);
    jetairways = BitmapFactory.decodeResource(this.getResources(),R.drawable.jet);
    airasia = BitmapFactory.decodeResource(this.getResources(),R.drawable.airasia);

    HahnAirSystems = BitmapFactory.decodeResource(this.getResources(),R.drawable.h1);
    Alitalia = BitmapFactory.decodeResource(this.getResources(),R.drawable.az);
    EtihadAirways = BitmapFactory.decodeResource(this.getResources(),R.drawable.ey);
    AirFacilities = BitmapFactory.decodeResource(this.getResources(),R.drawable.fz);
    GulfAir = BitmapFactory.decodeResource(this.getResources(),R.drawable.gf);
    SriLankanAirlines = BitmapFactory.decodeResource(this.getResources(),R.drawable.ul);
    OmanAviation = BitmapFactory.decodeResource(this.getResources(),R.drawable.wy);
    EmiratesAirlines = BitmapFactory.decodeResource(this.getResources(),R.drawable.ek);
    AirMauritius = BitmapFactory.decodeResource(this.getResources(),R.drawable.mk);
    TurkishAirlines = BitmapFactory.decodeResource(this.getResources(),R.drawable.tk);
    EthiopianAirlinesSC = BitmapFactory.decodeResource(this.getResources(),R.drawable.et);
    KenyaAirways = BitmapFactory.decodeResource(this.getResources(),R.drawable.kq);
    ThaiAirwaysInternational = BitmapFactory.decodeResource(this.getResources(),R.drawable.tg);
    SaudiArabianAirlines = BitmapFactory.decodeResource(this.getResources(),R.drawable.sv);

    next.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            Toast.makeText(View_fligh_info.this,"HELLO WORLD",Toast.LENGTH_LONG).show();

        
    );


    if (FlightHome.oneway.isChecked())
    


        Toast.makeText(View_fligh_info.this,"Oneway Trip",Toast.LENGTH_LONG).show();
        return_text.setVisibility(View.GONE);
        retur_text_2.setVisibility(View.GONE);


       //flight_information.setAdapter(null);
        flight_one_way_detail =new ArrayList<Flight_info_details>();
        flight_one_way_detail.clear();
        for (int i = 0; i <FlightTboSearch.flight_name_jeet.size(); i++) 

            flight_one_way_detail.add(new Flight_info_details(FlightTboSearch.flight_name_jeet.get(i).toString(), FlightTboSearch.flight_departure_jeet.get(i), FlightTboSearch.flight_arrival_jeet.get(i), FlightTboSearch.flight_name_jeet.get(i).toString()));

            flight_one_way_adapter = new Flight_info_adapter(View_fligh_info.this, flight_one_way_detail);

        

        flight_one_way_adapter.notifyDataSetChanged();
        flight_information.setAdapter(flight_one_way_adapter);


  //flight_one_way_detail.getAdapter().notify();


        int totalHeight = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(flight_information.getWidth(), View.MeasureSpec.AT_MOST);
        for (int i = 0; i < flight_one_way_adapter.getCount(); i++) 
            View listItem = flight_one_way_adapter.getView(i, null, flight_information);
            listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        

        ViewGroup.LayoutParams params = flight_information.getLayoutParams();
        params.height = totalHeight + (flight_information.getDividerHeight() * (flight_one_way_adapter.getCount() - 1));
        flight_information.setLayoutParams(params);
        flight_information.requestLayout();



    


@Override
public void onBackPressed() 


    flight_one_way_detail.clear();
 //     flight_information.setAdapter(null);

    Intent i=new Intent(View_fligh_info.this,FlightTboSearch.class);
    startActivity(i);






答案

我不知道你的逻辑是什么设置适配器。但是你永远不应该在内部循环创建适配器,所以纠正下面的事情

for (int i = 0; i <FlightTboSearch.flight_name_jeet.size(); i++) 
        flight_one_way_detail.add(new Flight_info_details(FlightTboSearch.flight_name_jeet.get(i).toString(), FlightTboSearch.flight_departure_jeet.get(i), FlightTboSearch.flight_arrival_jeet.get(i), FlightTboSearch.flight_name_jeet.get(i).toString()));
    
    flight_one_way_adapter = new Flight_info_adapter(View_fligh_info.this, flight_one_way_detail);
    flight_information.setAdapter(flight_one_way_adapter);

第二件事是onbackPressed()。因为我看到你没有完成当前活动的后退按钮,为什么会这样?我认为你应该完成你的活动,在这种情况下不需要重置适配器。 或者如果你想保持这种方式。然后只是清除列表将重置适配器。

@Override
public void onBackPressed() 

if(flight_one_way_adapter!=null)
flight_one_way_detail.clear();
flight_one_way_adapter.notifyDataSetChanged();
 
Intent i=new Intent(View_fligh_info.this,FlightTboSearch.class);
startActivity(i);
 
另一答案
public ArrayList<Flight_info_details> flight_one_way_detail; 

flight_one_way_detail是静态的,不应该是。

作为静态概念,只有一个对象flight_one_way_detail是你的活动的初始化,所以即使从其他活动回来后你仍然会得到那个对象而你正在其中添加新的航班细节,以便它显示旧的和新的

另外@Raghavendra建议创建新的适配器不应该在循环中。

另一答案

你应该只打电话给new Flight_info_adapter()一次。我建议首先创建ArrayList然后将其传递给Flight_info_adapter()构造函数:

ArrayList<Flight_info_detail> flight_one_way_detail = new ArrayList<>();
for (int i = 0; i <FlightTboSearch.flight_name_jeet.size(); i++) 
    flight_one_way_detail.add(new Flight_info_details(FlightTboSearch.flight_name_jeet.get(i).toString(), FlightTboSearch.flight_departure_jeet.get(i), FlightTboSearch.flight_arrival_jeet.get(i), FlightTboSearch.flight_name_jeet.get(i).toString()));


flight_one_way_adapter = new Flight_info_adapter(View_fligh_info.this, flight_one_way_detail);

创建列表后无需立即调用clear()。新列表保证为空。

请注意,适配器中的值仅存储在内存中。如果用户退出您的应用,则所有数据都将丢失。为了更加永久地保存数据,我建议您创建一个SQLite数据库并使用CursorAdapter。有几个很好的在线教程和博客说明了如何做到这一点。

另一答案

首先,在您的适配器中,您的arraylist不应该是静态的。

第二,为你的活动制作私人方法。像这样-

private ArrayList<modelclass> getdata()

        ArrayList<modelclass> flight_one_way_detail = new ArrayList<>() ;
        flight_one_way_detail.clear();
        flight_one_way_detail.add(new Flight_info_details(FlightTboSearch.flight_name_jeet.get(i).toString(), FlightTboSearch.flight_departure_jeet.get(i), FlightTboSearch.flight_arrival_jeet.get(i), FlightTboSearch.flight_name_jeet.get(i).toString()));
        return list ;
    

然后从onCreate方法将arraylist传递给你的适配器。

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.my_list_view);
        listViewAdapter = new ListViewAdapter(this, getdata()) ;
        listView.setAdapter(listViewAdapter);
    

我希望通过这两个步骤,你将得到你渴望的结果。如果没有发生,那么从你的适配器的构造函数中清除你的arraylist。像这样-

public ListViewAdapter(Activity activity, ArrayList<modelclass> list)
        this.list.clear();
        this.activity=activity;
        this.list=list;
        inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    

但是,这不是一个好习惯。因为,每次你向你的适配器传递全新的arraylist。当且仅当您没有获得所需结果时,您可以从构造函数中清除列表。

另一答案

首先,你不应该在onBackPressed()函数中启动新的活动。它的基本功能是返回上一个活动。在此函数之后,先前活动的onResume()函数运行并在那里,您应该更新列表和适配器。

以上是关于android的ListView如何追加数据?的主要内容,如果未能解决你的问题,请参考以下文章

Android - ArrayAdapter 重复 ListView 项目

android listView 滑动载入数据 该数据是服务端获取的

如何在 android listview 中设置页脚以动态拉伸到底部?

如何根据 android studio 中的 listview 项目点击更改活动图像和文本? java 或 kotlin

android listview 如何实现这种圆角和按下的效果,送分题又来了,求高手快来拿分

Android高手进阶教程(十六)之---Android中万能的BaseAdapter(Spinner,ListView,GridView)的使用!