如何从这种情况传递变量String?

时间:2012-10-17 13:09:38

标签: android variables android-asynctask

我有三个不同的项目。 Project1(isLibrary),Project2和Project3将Project1设置为Library。现在,我的问题是我向服务器发送请求,但我无法将我的Project2中的String传递给Project1。项目3也将使用Project1并将发送不同的请求。任何想法?

在我的Project1中,我有一个TestAsyncTask类。

public class TestAsyncTask extends AsyncTask<String, Void, String> {

TextView textView1[], textView2[]; 
TextView textView;
private LinearLayout linearLayout;
//It's just a sample, not a valid soap header
String string1 = "http://soapactionheaderline"; //Provides the value for the SOAPAction header line. 
//It's just a sample, not valid server
String string2 = "https://server.com"; //This is the target URL/Server that we will be connecting to.
Context context;
int resultInt;

//Constructor
public TestAsyncTask(Context cContext){
    context = cContext; //Pass Context to constructor
}

//Getter for LinearLayout.
public LinearLayout getLinearLayout(){
    return linearLayout;
}
//Setter for LinearLayout.
public void setLinearLayout(LinearLayout lLinearLayout){
    this.linearLayout = lLinearLayout;
}

//Getter for String.
public String getString(){
    return string2;
}
//Setter for String.
public void setString(String sString){
    this.string2 = sString;
}


@Override
protected String doInBackground(String... aServerConnectionString) {

String resultString = null; 

try {

    // Uses URL and HttpURLConnection for server connection.
    URL uRL = new URL(string2); 
    HttpURLConnection httpURLConnection = (HttpURLConnection) uRL.openConnection(); 
    httpURLConnection.setDoOutput(true); 
    httpURLConnection.setDoInput(true); 
    httpURLConnection.setUseCaches(false); 
    httpURLConnection.setChunkedStreamingMode(0); 

    //.addRequestProperty - Adds the given property to the request SOAPAction header
    httpURLConnection.addRequestProperty("SOAPAction", string1); 
    httpURLConnection.addRequestProperty("Content-Type", "text/xml; charset=utf-8"); 
    httpURLConnection.addRequestProperty("Content-Length", "" + "THIS IS WHERE I NEED TO PASS THE STRING VARIABLE FROM MY Project2".length()); 
    httpURLConnection.setRequestMethod(HttpPost.METHOD_NAME); 

    // Using OutputStream and Writer to send a request to the server.
    OutputStream outputStream = httpURLConnection.getOutputStream(); 
    Writer writer = new OutputStreamWriter(outputStream); 
    writer.write("THIS IS WHERE I NEED TO PASS THE STRING VARIABLE FROM MY Project2"); 
    writer.flush(); 
    writer.close(); 

    // Using InputStream to get the response of the request from the server.
    InputStream inputStream = httpURLConnection.getInputStream(); 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50); 

    int aint = httpURLConnection.getResponseCode(); 

    while ((aint = bufferedReader.read()) != -1) {
        byteArrayBuffer.append(aint); //Read bytes to the Buffer until there is nothing more to read.
    }

    resultString = new String(byteArrayBuffer.toByteArray()); 

    // Use SAXParser(Simple API for XML) to handle the parsing of XML(Response). 
    SAXParserFactory sAXParserFactory = SAXParserFactory.newInstance(); 
    SAXParser sAXParser = sAXParserFactory.newSAXParser(); 
    XMLReader xMLReader = sAXParser.getXMLReader(); 
    // Create handler to handle XML Tags
    TestXMLHandler xMLHandler = new TestXMLHandler(); 
    xMLReader.setContentHandler(xMLHandler); 
    InputSource inputSource = new InputSource(new StringReader(resultString)); 
    xMLReader.parse(inputSource); 

    } catch (Exception exception) {
    resultString = exception.getMessage(); in the created String and display it to UI.
    }
    return resultString; 
}

//This step is the return-value from doInBackground.
protected void onPostExecute(String aReturnValueString) {

    // Create an object/instance of GBData Class and get results from GBXMLHandler. 
    TestGetterSetter data = TestXMLHandler.testdata; 

    int sizeInt = data.getOperatorName().size();

    textView1 = new TextView[sizeInt];  
    textView2 = new TextView[sizeInt]; 

    //The for statement provides a compact way to iterate over a range of values.
    for (resultInt = 0; resultInt < sizeInt; resultInt++) {

    textView1[resultInt] = new TextView(context.getApplicationContext()); 
    textView1[resultInt].setText("OperatorName = " + data.getOperatorName().get(resultInt)); 
    linearLayout.addView(textView1[resultInt]); 

    textView2[resultInt] = new TextView(context.getApplicationContext()); 
    textView2[resultInt].setText("type = " + data.getType().get(resultInt)); 
    linearLayout.addView(textView2[resultInt]);

    }
}
}

在我的Project2中,我有TestActivity1类,它扩展了活动,它是UI

public class TestActivity1 extends Activity{

    TestAsyncTask asyncTask = new TestAsyncTask(this);

    //This is just a sample soap
    String requestString = "<soapenv---------------------------------------------------------------->";

    @Override
    public void onCreate(Bundle aBundle) {
        super.onCreate(aBundle);            

        asyncTask.execute(asyncTask.getString());

        LinearLayout linearLayout = asyncTask.getLinearLayout();
        linearLayout = new LinearLayout(this); 
        linearLayout.setOrientation(1); 
        asyncTask.setLinearLayout(linearLayout); 

        // Set the ContentView to layout for display
        setContentView(linearLayout);
    }
}

3 个答案:

答案 0 :(得分:0)

我真的不知道你在代码中想要实现的目标。无论如何,遇到问题,我认为你已经将一个字符串值传递给你的AsyncTask。您需要做的就是在 doInBackground 方法中使用它。例如:

protected String doInBackground(String... aServerConnectionString) {
   String yourValue = aServerConnectionString[0];

   ...
   ...
   ...

   writer.write(yourValue);  //pass your value to writer

   ...
   ...
   ...
}

P.S。我相信你的代码不会运行,因为它在某些地方似乎不合逻辑

答案 1 :(得分:0)

首先,我认为您阅读AsyncTask非常重要,因为您的实施没有正确地利用其设计工作方式。如果我诚实,你已经给自己带来了更多问题:)

要根据您当前的实施解决问题,请务必了解execute()功能如何与doInBackground()结合使用。

Execute为其参数接受一个字符串数组,因此在Project2中你可以这样做:

String url = "";
String request = "";
asyncTask.execute(url, request);

然后在您的ASyncTask中,doInBackground方法接收您用于execute方法的参数。当您在类之间传递所需的值时,您的doInBackground方法可能如下所示:

@Override
protected String doInBackground(String... aServerConnectionString) {
String url, request;

if (aServerConnectionString[0] != null) {
    url = aServerConnectionString[0];
}

if (aServerConnectionString[1] != null) {
    request = aServerConnectionString[1];
}

这样你的ASyncTask可以删除所有与字符串相关的东西,因为它依赖于Project2 / 3来传递字符串。

答案 2 :(得分:0)

将字符串保存在您的库项目中的strings.xml以及目标项目中。总是将资源的最高优先级提供给目标项目。因此,您可以引用相同的ID并将凝视发送到服务器而不会出现任何问题< / p>