listview of the android development tutorial displays sqlite data

  • 2020-05-27 07:10:50
  • OfStack


package com.it.db;
import java.util.List;
import com.it.dao.PersonDao;
import com.it.domain.Person;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
 private ListView lv;
 private List<Person> persons;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  PersonDao dao=new PersonDao(this);
  persons=dao.findAll();
  lv=(ListView) findViewById(R.id.lv);
  lv.setAdapter(new MyAdapter());

  lv.setOnItemClickListener(new OnItemClickListener() {
   // Click data   Posted on the 1 a activity
   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    // TODO Auto-generated method stub
    Person mperson=persons.get(position);
    String number=mperson.getNumber();
    Intent data=new Intent();
    data.putExtra("number", number);
    setResult(0, data);
    // Click on the   Shut down this activity
    finish();
   }
  });
 }

 private class MyAdapter extends BaseAdapter{
  private static final String TAG = "MyAdapter";
  /**
   *  control listview How many entries are there in it 
   */
  @Override
  public int getCount() {
   // TODO Auto-generated method stub
   return persons.size();
  }
  @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
   return null;
  }
  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return 0;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   // TODO Auto-generated method stub
   /**
    *  using inflater According to 
    */
   Person person=persons.get(position);
   View view=View.inflate(MainActivity.this, R.layout.list_item, null);

   TextView tv_id=(TextView) view.findViewById(R.id.tv_id);
   tv_id.setText("id:"+person.getId());

   TextView tv_name=(TextView) view.findViewById(R.id.tv_name);
   tv_name.setText(" The name :"+person.getName());

   TextView tv_number=(TextView) view.findViewById(R.id.tv_number);
   tv_number.setText(" The phone :"+person.getNumber());

   return view;
   }
   /**
    *  Don't have to inflater
    *
   Log.i(tag, " location "+position);   // See the effect 
   TextView tv=new TextView(getApplicationContext());
   tv.setTextSize(20);
   tv.setTextColor(Color.BLACK);
   // An entry at each location 
   Person person=persons.get(position);
   tv.setText(person.toString());
   return tv;
  }*/

 }
}


Related articles: