-1

我正在尝试从 web 服务获取数据并根据 web 服务的响应创建动态自定义字段。然后用户将填写字段,然后单击上传按钮后,它将数据从动态自定义字段发送到网络服务,然后开始上传。我想知道如何从自定义字段中获取数据,因为它们是动态创建的,我无法访问它们。这是我的代码。这是我在从 web 服务获得响应后创建字段的图片,我需要您的帮助。

在此处输入图像描述

package com.isoft.uploader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

public class UploaderActivity extends Activity 
{
ArrayList <Response> WebData= new ArrayList<Response>();
public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";
final String NAMESPACE = "http://tempuri.org/";
final String SERVICEURL = "http://192.168.10.177/androidws/isandroidws.asmx";
final String METHOD_NAME1="OzelVeriAlanlariniGetir";
final String METHOD_NAME="KullaniciGiris";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button enter=(Button)findViewById(R.id.Enter);
    final EditText username=(EditText)findViewById(R.id.username);
    final EditText password=(EditText)findViewById(R.id.password);
    final  AlertDialog ad=new AlertDialog.Builder(this).create();
    enter.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View arg0) 
        {
            // TODO Auto-generated method stub
            //request code for Webservice
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
            //sending the username to the webservice
            request.addProperty("kullaniciAdi",username.getText().toString());
            //sending the password to the webservice
            request.addProperty("password",password.getText().toString());
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            //Putting the request in an envelope
            envelope.setOutputSoapObject(request);
            HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
            Object response = null;
            try
            {
                 transport.call("http://tempuri.org/"+METHOD_NAME, envelope);
                 //getting the response from the webservice
                 response= envelope.getResponse();
            }
            catch(Exception exception)
            {
                exception.printStackTrace();
            }//end of catch
            if(response!=null && Integer.parseInt(response.toString()) != 0)
            {
                openGaleryVideo();
            }//end of if
            else
            {
                ad.setMessage("Lütfen Kullanıcı Adınızı ve Şifrenizi Kontrol Ediniz.");
                ad.show();  
            }//end of else
        }//end of onClick method    
    });//end of OnclickListener method
}//end of onCreate method
public void openGaleryVideo()
{
    Intent intent=new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}//end of openGaleryVideo method

public String getPath(Uri uri)
{   
    String[] projection = { MediaStore.Video.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}//end of getPath method

//Response Class
public class Response
{
    int Id;
    String Name;
    String Type;
    String Value;
    String DefaultValue;
    int Flag;
    int Index;
}//end of Response class

//onActivityResult
@SuppressWarnings("unused")
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        if (requestCode == SELECT_VIDEO) 
        {
            Uri videoUri = data.getData();
            path=getPath(videoUri);
            ScrollView scroll = new ScrollView(this);
            LinearLayout layout=new LinearLayout(this);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
            scroll.addView(layout,new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            setContentView(scroll);             
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            //İsteğimizi zarf'a koyuyoruz
            envelope.setOutputSoapObject(request);
            HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
            final  AlertDialog adr=new AlertDialog.Builder(this).create();
            Object response1=null;
            try
            {
                 transport.call("http://tempuri.org/"+METHOD_NAME1, envelope);
                 //getting the response from the webservice
                 response1 =envelope.getResponse();
                 JSONArray jArray= new JSONArray(response1.toString());
                 for(int i=0;i<jArray.length();i++)
                 {
                     JSONObject json_data= jArray.getJSONObject(i);
                     Response result= new Response();
                     result.Id= json_data.getInt("Id");
                     result.Name= json_data.getString("Name");
                     result.Type= json_data.getString("Type");
                     result.Value=json_data.getString("Value");
                     result.DefaultValue=json_data.getString("DefaultValue");
                     result.Flag=json_data.getInt("Flag");
                     result.Index=json_data.getInt("Index");
                     WebData.add(i,result);
                 }//end of for loop     
            }//end of try 
            catch(Exception exception)
            {
                exception.printStackTrace();
            }//end of catch

            for(int j=0;j<WebData.size();j++)
            {
                TextView t= new TextView(this);
                t.setText(WebData.get(j).Name);
                layout.addView(t);
                if("Type"=="datetime")
                {
                    EditText datetime= new EditText(this);
                    datetime.setId(j);
                    SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd" ); 
                    datetime.setText(sdf.format( new Date()));
                    layout.addView(datetime);

                }//end of if

                else if("Type"=="int")
                {
                    EditText integer= new EditText(this);
                    layout.addView(integer);
                }//end of else if
                else
                {
                    EditText nvarchar= new EditText(this);
                    layout.addView(nvarchar);
                }//end of else 

            }//end of for loop
            Button button= new Button(this);
            button.setClickable(true);
            button.setText("Yükle");
            layout.addView(button);
            button.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0)
                {
                    // TODO Auto-generated method stub

                }
            });
        }//end of If request code
    }//end of If result code
}//end of onActivityResult
}//end of main
4

3 回答 3

3

如果我理解正确,您的问题是从动态创建的字段中获取数据。EditText您可以通过保存在您的类中动态创建的来解决它。

这是您保存字段的代码(我没有检查语法)。我已经用 //BUBBLE 注释标记了更改的块。

package com.isoft.uploader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

public class UploaderActivity extends Activity 
{
  ArrayList <Response> WebData= new ArrayList<Response>();
  public static final int SELECT_VIDEO=1;
  public static final String TAG="UploadActivity";
  String path="";
  final String NAMESPACE = "http://tempuri.org/";
  final String SERVICEURL = "http://192.168.10.177/androidws/isandroidws.asmx";
  final String METHOD_NAME1="OzelVeriAlanlariniGetir";
  final String METHOD_NAME="KullaniciGiris";

  // BUBBLE
  private List<EditText> dynaFields = null;

  /** Called when the activity is first created. */
  @Override
    public void onCreate(Bundle savedInstanceState) 
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      Button enter=(Button)findViewById(R.id.Enter);
      final EditText username=(EditText)findViewById(R.id.username);
      final EditText password=(EditText)findViewById(R.id.password);
      final  AlertDialog ad=new AlertDialog.Builder(this).create();
      enter.setOnClickListener(new View.OnClickListener() 
          {
          @Override
          public void onClick(View arg0) 
          {
          // TODO Auto-generated method stub
          //request code for Webservice
          SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
          //sending the username to the webservice
          request.addProperty("kullaniciAdi",username.getText().toString());
          //sending the password to the webservice
          request.addProperty("password",password.getText().toString());
          SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
          envelope.dotNet = true;
          //Putting the request in an envelope
          envelope.setOutputSoapObject(request);
          HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
          Object response = null;
          try
          {
          transport.call("http://tempuri.org/"+METHOD_NAME, envelope);
          //getting the response from the webservice
          response= envelope.getResponse();
          }
          catch(Exception exception)
          {
            exception.printStackTrace();
          }//end of catch
          if(response!=null && Integer.parseInt(response.toString()) != 0)
          {
            openGaleryVideo();
          }//end of if
          else
          {
            ad.setMessage("Lütfen Kullanıcı Adınızı ve Şifrenizi Kontrol Ediniz.");
            ad.show();  
          }//end of else
          }//end of onClick method    
          });//end of OnclickListener method
    }//end of onCreate method
  public void openGaleryVideo()
  {
    Intent intent=new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
  }//end of openGaleryVideo method

  public String getPath(Uri uri)
  {   
    String[] projection = { MediaStore.Video.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
  }//end of getPath method

  //Response Class
  public class Response
  {
    int Id;
    String Name;
    String Type;
    String Value;
    String DefaultValue;
    int Flag;
    int Index;
  }//end of Response class

  //onActivityResult
  @SuppressWarnings("unused")
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK)
      {
        if (requestCode == SELECT_VIDEO) 
        {
          Uri videoUri = data.getData();
          path=getPath(videoUri);
          ScrollView scroll = new ScrollView(this);
          LinearLayout layout=new LinearLayout(this);
          layout.setOrientation(LinearLayout.VERTICAL);
          layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
          scroll.addView(layout,new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
          setContentView(scroll);             
          SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
          SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
          envelope.dotNet = true;
          //İsteğimizi zarf'a koyuyoruz
          envelope.setOutputSoapObject(request);
          HttpTransportSE transport = new HttpTransportSE(SERVICEURL);
          final  AlertDialog adr=new AlertDialog.Builder(this).create();
          Object response1=null;
          try
          {
            transport.call("http://tempuri.org/"+METHOD_NAME1, envelope);
            //getting the response from the webservice
            response1 =envelope.getResponse();
            JSONArray jArray= new JSONArray(response1.toString());
            for(int i=0;i<jArray.length();i++)
            {
              JSONObject json_data= jArray.getJSONObject(i);
              Response result= new Response();
              result.Id= json_data.getInt("Id");
              result.Name= json_data.getString("Name");
              result.Type= json_data.getString("Type");
              result.Value=json_data.getString("Value");
              result.DefaultValue=json_data.getString("DefaultValue");
              result.Flag=json_data.getInt("Flag");
              result.Index=json_data.getInt("Index");
              WebData.add(i,result);
            }//end of for loop     
          }//end of try 
          catch(Exception exception)
          {
            exception.printStackTrace();
          }//end of catch

          // BUBBLE create a list with the exact size of input fields
          this.dynaFields = new ArrayList<EditText>(WebData.size());

          for(int j=0;j<WebData.size();j++)
          {
            //BUBBLE: instantiate and add the current field to the list and view
            EditText newField = new EditText(this);
            this.dynaFields.add (newField)
            layout.addView(newField);

            TextView t= new TextView(this);
            t.setText(WebData.get(j).Name);
            layout.addView(t);
            if("Type"=="datetime")
            {
              //BUBBLE
              newField.setId(j);
              SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd" ); 
              newField.setText(sdf.format( new Date()));

            }//end of if

          }//end of for loop
          Button button= new Button(this);
          button.setClickable(true);
          button.setText("Yükle");
          layout.addView(button);
          button.setOnClickListener(new View.OnClickListener() {

              @Override
              public void onClick(View arg0)
              {
              // TODO Auto-generated method stub

              }
              });
        }//end of If request code
      }//end of If result code
    }//end of onActivityResult
}//end of main

简而言之,我创建了一个 ArrayListEditText

private List<EditText> dynaFields = null;

然后列表在字段创建之前被实例化:

// BUBBLE create a list with the exact size of input fields
this.dynaFields = new ArrayList<EditText>(WebData.size());

最后,一旦创建了字段,我就将它们添加到列表和视图中:

// instantiate and add the current field to the list and view
EditText newField = new EditText(this);
this.dynaFields.add (newField)
layout.addView(newField);

我在你的 if 语句中做了一些小的简化,所以我可以只使用一个 EditText 对象。

要获取组件,只需在 onClick 方法中遍历数组:

public void onClick(View arg0)
{
    TextField currText;
    for (currText : UploaderActivity.this.dynaFields) {
     // TODO: get the current EditText text and have fun!
    }    
}
于 2012-07-13T14:38:54.653 回答
2

创建时在 EditText 对象上设置标签(result.Id),然后浏览主布局,然后

int mainChildsCount = mainGroup.getChildCount();
for(int i=0;i<mainChildsCount;i++){
    View v = mainGroup.getChildAt(i);   
    if(v instanceof EditText){
        //recognize them here by their tags     
    }
}
于 2012-07-13T14:49:39.493 回答
0

Take

int dynId = 1001;

Now, when you are creating EditTexts dynamically, set their ids by using

.setId(dynId++);

Then at the time of sending EditTexts' data to web-service; retrive values from EditTexts by getting them using ID you have seted at the time of creating.

At time of retriving, you can start retriving using 1001 and increment them by 1.


use this :

    String unm, pwd;

    YourComponent.setOnClickListener(new View.OnClickListener() {  //  OR  In  onClick

                @Override
                public void onClick(View arg0)
                {
                     unm = username.getText().toString();
                     pwd = password.getText().toString();
                }
            });

Now, use these unm and pwd strings.

You can get the components by their ID's

for (int i = 1001; i < 1001 + componentCount; i++) {
  View currView = getViewById (i);
  if (currView instanceof EditText) { 
      EditText currentComponent = (EditText) currView;
  }
}
于 2012-07-13T14:30:34.423 回答