2011-03-19 4 views
0

필요한 도움의 범위가 확실하지 않지만 방금 올바른 방향을 가리키고 있다고해도 나는 물을 것이라고 생각했습니다.http 입력에서 목록 활동을 표시하는 클래스를 작성하는 데 도움이 필요합니다.

텍스트 상자 및 제출 버튼이있는 기본 레이아웃이 있습니다.

hellodatabase 클래스와 함께 텍스트보기로 결과를 retune 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; 
}  

} 
+0

값을 반복하는 동안 모든 값을 ArrayList에 추가 한 다음 Iterator를 사용하여 String Array로 변환합니다. 사용자 지정 어댑터를 사용하고 목록보기를 부 풀린 다음 텍스트를 설정하거나 모든 Ada 당신이 좋아하는대로 ... list_fname.add (jo.getString ("Value")); string [] VALUE_fname = 새 문자열 [list_fname.size()]; 반복기 it = list_fname.iterator(); while (it.hasNext()) { fn ++; VALUE_fname [fn] = it.next(). toString(); }이 문자열 배열을 어댑터 – Venky

+0

으로 설정하십시오. Venkatesh는 내가해야 할 일이 무엇인지 이해하고 있지만 지금 당장은 어떻게 작동하는지 많이 알지 못합니다.이 클래스를 작성하면로드에 도움이 될 것입니다. –

답변

0

검사 기준이 link .. 당신은 .. 당신이 이해하기 쉬울 것이다 ListView..this에서 삭제, 테이블을 만들고 데이터를 추가, 편집 모두 당신이 필요로하는

+0

많은 SQLite 튜토리얼을했는데 위의 클래스에서 데이터를 표시하는 데 list 뷰가 필요하다. –

0

먼저 볼 수 있습니다 ListActivity를 확장하려면 ListActivity에 ListView 행을 포함하는 ListView와 데이터를 받고 ListView 내에 레이아웃을 작성하는 어댑터가 있어야합니다.

Json String에 데이터가 있으므로 각 행에 Json 문자열 항목이 저장됩니다.

가장 중요한 것은 어댑터이며 어댑터는 ListView 생성을 담당합니다. 위에서 언급 한 작업을 수행하려면 어댑터를 ListActivity의 내부 클래스로 선언해야합니다. 구조는이 될 것입니다 :

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

희망이 도움을

을 여기

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

완벽한 예 (의사에)

관련 문제