需要帮助构建一个从http输入显示列表活动的类

时间:2011-03-19 13:00:45

标签: android mysql database

我不确定我需要的帮助程度,但我想我会问,即使我只是指向了正确的方向。

我有一个带文本框和提交按钮的基本布局。

我有一个名为hellodatabase的类,它向php文件发送一个字符串,将结果重新调整为文本视图。

我需要做的是将字符串发送到hellodatabase类,然后显示结果。

下面是我在我用于数据库连接的教程中找到的一个类。

创建这个课程的任何帮助都会很棒,或者只是指向正确的方向。

package example.hellodatabase;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;


public class HelloDatabase extends Activity {
/** Called when the activity is first created. */

   TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources  
    // but since its an example saves declaring them in the XML.  
    LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
    txt = new TextView(getApplicationContext());  
    rootLayout.addView(txt);  
    setContentView(rootLayout);  

    // Set the text and call the connect function.  
    txt.setText("Connecting..."); 
  //call the method to run the data retreival
    txt.setText(getServerData(KEY_121)); 



}
public static final String KEY_121 = "http://www.mydomain.co.uk/1.php"; //i use my real ip here



private String getServerData(String returnString) {

   InputStream is = null;

   String result = "";
    //the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("name","beans"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);

                    //Get an output to the screen
            }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return returnString; 
}    

}

1 个答案:

答案 0 :(得分:0)

首先,你需要扩展ListActivity,ListActivity必须包含一个ListView(包含ListView行)和一个接收数据并在ListView中构建布局的Adapter。

您将数据存入Json字符串,因此,每行将包含一个Json字符串条目。

最重要的是Adapter,适配器负责ListView的创建。您必须将适配器声明为ListActivity的内部类,以便执行上述操作。结构将是这样的:(在伪代码上)

MyActivity extends ListActivity{
   ListView listView;

   MyAdapter extends ArrayAdapter<DataBean>{
     public MyAdapter(Context context, int textViewResourceId, List<Object> objects) {
       //here you initialize all your stuff and helper things
     }
   }

   @Override
   public View getView(final int position, View convertView, ViewGroup parent) {
       //this is the most important method cause this will make the layout for a single row.
   }
}

这是一个完整的例子:

public class PeopleList extends ListActivity {

    private ListAdapter listAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String data = getServerData();
        //split the data and pass to the adapter like a List<String>
        listAdapter = new PeopleListAdapter(this, R.id.listItemFirstLine, data);
        setListAdapter(listAdapter);
        registerForContextMenu(getListView());
        getListView().setBackgroundDrawable(getResources().getDrawable(R.drawable.background_new_search_activity_1));
        getListView().setCacheColorHint(Color.parseColor("#00000000"));
    }

    class PeopleListAdapter extends ArrayAdapter<String> {

        /**
        * This method will construct the ArrayAdapter and add the objects String List to its inner List.
        */
        public PeopleListAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);
        }

        /**
        * Here we inflate a xml layout and put into a view (convertView)
        * We set the necessary data into a static class (for performance reasons)
        * Setting the itemHolder like a tag of the 'convertView' will put the ItemViewHolder inner views
        * (TextView title, TextView description and ImageView icon) as the convertView childs views.
        *   Param: position will return the position for wich we are constructing the view
        *          convertView, the view that we have to build and return 
        *          parent, is the ListView
        */
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(ctx);
            itemHolder = new ItemViewHolder();
            if(convertView == null){
                //inflate the xml layout and assign like child view of the parent parameter.
                convertView = inflater.inflate(R.layout.lista_propiedades, parent, false);
                convertView.setTag(itemHolder);
            }
            itemHolder.title = ((TextView)convertView.findViewById(R.id.listItemFirstLine));
            itemHolder.description = ((TextView)convertView.findViewById(R.id.listItemSecondLine));
            itemHolder.operationIcon = ((ImageView)convertView.findViewById(R.id.operationIcon));
            itemHolder.title.setText( getItem(position) );
            itemHolder.description.setText( getItem(position) );
            return convertView;
        }

    }

    static class ItemViewHolder{
        TextView title;
        TextView description;
        ImageView operationIcon;
    }

}

Later is the xml layout that corresponds to each row: R.layout.lista_propiedades

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dip"
    android:background="@drawable/transparent_selector">

    <ImageView
        android:id="@+id/operationIcon"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="6dip"
        android:src="@drawable/pin_home_any" />

    <TextView
        android:id="@+id/listItemFirstLine"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_toRightOf="@id/icon"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:textColor="#FF333333"
        android:gravity="center_vertical"
        android:text="My Application" />

    <TextView  
        android:id="@+id/listItemSecondLine"

        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 

        android:layout_toRightOf="@id/icon"
        android:layout_below="@id/listItemFirstLine"
        android:textColor="#FF666666"
        android:maxLines="5"
        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sit amet dui nunc. Suspendisse scelerisque quam non massa mollis eleifend. Ut dapibus fermentum leo, ac mattis enim fringilla eu. Praesent non lorem ut orci facilisis pulvinar. Fusce pretium lorem non erat interdum quis sodales massa dapibus. Maecenas varius varius elementum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas sem magna, rutrum eget aliquet vitae, lacinia sit amet purus. Integer odio magna, euismod in luctus ut, ullamcorper at nisl. Phasellus ullamcorper, nisl a posuere tristique, augue justo tincidunt velit, eget placerat ligula sem eget augue. Morbi tempus, felis vel mattis pharetra, lacus massa suscipit tortor, vel laoreet dui nulla quis nulla. Praesent scelerisque fermentum neque ut vulputate. Pellentesque in urna sit amet lorem auctor porta a non libero. Nam ac sem ac dui ornare interdum. Aliquam scelerisque, nibh vitae interdum scelerisque, metus arcu iaculis nisi, id sagittis orci augue consectetur purus. " />

</RelativeLayout>

我建议您观看此视频:The World of ListView