Android My12306项目(二)

本文介绍了如何在Android应用中实现联系人列表展示,包括从服务器获取数据填充ListView,设置ActionBar,传递数据,对话框的使用,以及添加、更新联系人和查看详情的实现。讲解了各个关键步骤和技术点,如Intent数据传递,AlertDialog的多种类型,以及ListView的更新方法。
摘要由CSDN通过智能技术生成

我的联系人列表

在这里插入图片描述
访问http://localhost/getcontactByuserid获得联系人列表显示在listview控件上
activity_mycontact.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

    <ListView
        android:id="@+id/lv_mycontacts_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

   

</LinearLayout>

item_mycontacts_list.xml listView适配器项布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.77"
        android:orientation="vertical">

        <TextView
            android:id="@+id/item_tv_list_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" 
            android:textSize="16sp"
            android:layout_marginTop="10dp"/>

        <TextView
            android:id="@+id/item_tv_list_idcard"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" 
            android:textColor="@color/gray1"/>

        <TextView
            android:id="@+id/item_tv_list_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" 
             android:textColor="@color/gray1"/>
    </LinearLayout>

    <ImageView
        android:id="@+id/item_iv_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/forward_25" 
        android:layout_marginTop="30dp"/>

</LinearLayout>

MyContactActivity.java



public class MyContactActivity extends Activity{
   
	
	ListView mycontectsList;	
	//异步
	Handler handler;
	String userId;//存取父页面参数
	List<String> contactId;
	List<Map<String,Object>> contacts;//适配器数据
	SimpleAdapter adapter;	
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
   
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mycontact);
		
		//标题栏
		ActionBar actionBar=getActionBar();//得到标题栏
		actionBar.setDisplayHomeAsUpEnabled(true);//给左上角加一个返回图标
		
		 Bundle bundle=this.getIntent().getExtras();
		Log.i("MyContactActivity","ID:   "+bundle.getString("id"));
		userId=bundle.getString("id");
		mycontectsList=(ListView) findViewById(R.id.lv_mycontacts_list);
		
		//从数据库获取联系人列表
		getData();
		
		handler=new Handler(){
   
			public void handleMessage(Message msg) {
   
				if(msg.what==1){
   
					
					String response=(String)msg.obj;//json数组形式的字符串
					if(!"".equals(response)){
   
					//json数组解析
						try {
   						
							JSONArray arr=new JSONArray(response);
							contacts=new ArrayList();
							contactId=new ArrayList();
							for(int i=0;i<arr.length();i++){
   //不能使用加强for
								JSONObject obj=arr.getJSONObject(i);
								Map<String,Object> map=new HashMap();
								//取值对应contact类属性
								map.put("name", obj.getString("name")+"("+obj.getString("type")+")");
								map.put("idcard",obj.getString("idtype")+":"+obj.getString("idcard"));
								map.put("phone","电话号:"+obj.getString("phone"));
								contacts.add(map);							
								contactId.add(String.valueOf(obj.getInt("id")));
								
							}							
							
							//map的key值
							String[] from=new String[]{
   "name","idcard","phone"};
							int[] to=new int[]{
   R.id.item_tv_list_name,R.id.item_tv_list_idcard,R.id.item_tv_list_phone};
							
							
							
							//上下文   要显示的数据  项布局id   map的key   控件的id
							adapter=new SimpleAdapter(MyContactActivity.this, contacts, R.layout.item_mycontacts_list, from, to);
							mycontectsList.setAdapter(adapter);
							//listview项单机操作
							mycontectsList.setOnItemClickListener(new OnItemClickListener(){
   

								@Override
								public void onItemClick(AdapterView<?> parent,
										View view, int position, long id) {
   
									// TODO Auto-generated method stub
									//开启新窗口
									Intent intent=new Intent(MyContactActivity.this,MyContactDetailActivity.class);
									intent.putExtra("contacts", contacts.get(position).toString());//数据传递
									intent.putExtra("contactId", contactId.get(position).toString());
									
									//正常
									//startActivity(intent);
									//参数   意图,请求编码
									startActivityForResult(intent,1);//1项联系人详情页面发送一个requestCode
								}
								
							});
													
						
						} catch (JSONException e) {
   
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}else if(msg.what==2){
   
					Toast.makeText(MyContactActivity.this, "服务器错误", Toast.LENGTH_LONG).show();
				}
			};
		};
	
	}

	private void getData() {
   
		// TODO Auto-generated method stub
		new Thread(new Runnable(){
   

			@Override
			public void run() {
   
				// TODO Auto-generated method stub
				DefaultHttpClient httpClient=new DefaultHttpClient();
				HttpPost httpPost=new HttpPost("http://10.0.2.2/getcontactByuserid");
				//参数
				List<NameValuePair> params=new ArrayList();
				params.add(new BasicNameValuePair("userId",userId));
				//将参数转换成一个httpEntity 把参数付给post请求对象
				UrlEncodedFormEntity entity;
				try {
   
					entity = new UrlEncodedFormEntity(params,"utf-8");
					httpPost.setEntity(entity);
					HttpResponse httpResponse=httpClient.execute(httpPost);
					if(httpResponse.getStatusLine().getStatusCode()==200){
   
						String response=EntityUtils.toString(httpResponse.getEntity(),"utf-8");
						//将数据返回
						Message msg=new Message();
						msg.what=1;
						msg.obj=response;//字符串用obj传回
						handler.sendMessage(msg);
					}else{
   
						//服务器访问失败,异步发送消息,弹框提示
						Message msg=new Message();
						msg.what=2;
						handler.sendMessage(msg);
					}
				} catch (ClientProtocolException e) {
   
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
   
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}).start();
	}
	
	//创建菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
   
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.mycontact_list, menu);
		return true;
	}

	//菜单项选择事件
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
   
		
		if (item.getItemId() == R.id.menu_contact_list_add) {
   
			//开启新窗口
			Intent intent=new Intent(MyContactActivity.this,MyContactAddActivity.class);
			intent.putExtra("userid", userId);
			//正常
			startActivityForResult(intent,3);//1项联系人详情页面发送一个requestCode

		}
		if(item.getItemId()==android.R.id.home){
   
			finish();//关闭当前的activity
		}
		
		return super.onOptionsItemSelected(item);
	}

	
	//接受从联系人详情回来的数据
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		switch(requestCode){
   
		case 1:
			if(resultCode==RESULT_OK){
   
				String newContacts=data.getStringExtra("newContacts");
				JSONArray arr;
				
				try {
   
					arr=new JSONArray(newContacts);
					contacts.get(requestCode).put("name",arr.getJSONObject(0).getString("value")+"("+arr.getJSONObject(3).getString("value")+")");
					contacts.get(requestCode).put("phone","电话号:"+arr.getJSONObject(4).getString("value"));
					adapter.notifyDataSetChanged();
				} catch (JSONException e) {
   
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			break;
			
		case 3:
			if(resultCode==RESULT_OK){
   
				String addContact=data.getStringExtra("addContact");
				Log.d("---",addContact+"");
				JSONArray arr;
				
				try {
   
					arr=new JSONArray(addContact);
					Map<String,Object> map=n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值