Android 需要帮助构建一个显示来自http输入的列表活动的类吗

Android 需要帮助构建一个显示来自http输入的列表活动的类吗,android,mysql,database,Android,Mysql,Database,我不确定我需要的帮助有多大,但我想我会问的,即使我只是被指向了正确的方向 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.H

我不确定我需要的帮助有多大,但我想我会问的,即使我只是被指向了正确的方向

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; 
}    

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

我有一个名为
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; 
}    

}
package example.hellodatabase;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.LinearLayout;
导入android.widget.TextView;
公共类HelloDatabase扩展活动{
/**在首次创建活动时调用*/
文本视图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//创建一个粗略的视图-这应该通过布局资源进行设置
//但是,因为这是一个示例,所以不需要在XML中声明它们。
LinearLayout rootLayout=新的LinearLayout(getApplicationContext());
txt=新文本视图(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
//设置文本并调用connect函数。
txt.setText(“连接…”);
//调用该方法以运行数据检索
setText(getServerData(KEY_121));
}
公共静态最终字符串键_121=”http://www.mydomain.co.uk/1.php“;//我在这里使用我的真实ip
私有字符串getServerData(字符串返回字符串){
InputStream=null;
字符串结果=”;
//要发送的年度数据
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“名称”、“bean”);
//http post
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(键号121);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(例外e){
e(“Log_标记”,“http连接错误”+e.toString());
}
//将响应转换为字符串
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
//解析json数据
试一试{
JSONArray jArray=新JSONArray(结果);

对于(int i=0;i首先,您需要扩展ListActivity,ListActivity必须包含一个ListView(其中包含ListView行)和一个适配器,该适配器接收数据并在ListView中构建布局

您将数据转换为Json字符串,因此,每一行都将保存一个Json字符串条目

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

MyActivity扩展了ListActivity{
列表视图列表视图;
MyAdapter扩展了ArrayAdapter{
公共MyAdapter(上下文上下文、int textViewResourceId、列表对象){
//在这里,您可以初始化所有的东西和助手
}
}
@凌驾
公共视图getView(最终整数位置、视图转换视图、视图组父视图){
//这是最重要的方法,因为这将使布局为一行。
}
}
这里有一个完整的例子:

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>
公共类PeopleList扩展了ListActivity{
私有ListAdapter ListAdapter;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
字符串数据=getServerData();
//拆分数据并像列表一样传递给适配器
listAdapter=新的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”);
}
类PeopleListAdapter扩展了ArrayAdapter{
/**
*此方法将构造ArrayAdapter并将对象字符串列表添加到其内部列表中。
*/
public PeopleListAdapter(上下文上下文、int-textViewResourceId、列表对象){
超级(上下文、textViewResourceId、对象);
}
/**
*这里我们膨胀一个xml布局并放入一个视图(convertView)
*我们将必要的数据设置为静态类(出于性能原因)
*将itemHolder设置为“convertView”的标记会将ItemViewHolder放置在内部视图中
*(Te)