0

抱歉,如果标题格式不正确。基本上这是我的问题:我的 Android 项目是一个 REST 客户端。webservice 项目包含一些数据,这些数据基本上可以为一个人制作个人资料(名字、姓氏等)。在我的 Android 客户端中,我有一个活动,上面有一个文本字段和一个按钮。Main 活动中的文本字段是用户输入帐号 (id=enter_acct) 的地方,该帐号指向特定人员,其详细信息在 Web 服务项目中。在我的 MainActivity java 文件中,我告诉按钮打开一个包含文本字段的新活动。换句话说,Main Activity 包含执行 GET 请求的所有代码。辅助 Activity 只是一个包含文本字段的布局。这是我的主要布局文件代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  ......
/>

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

<EditText
    android:id="@+id/enter_acct"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="34dp"
    android:ems="10"
    android:hint="@string/acct" />

<Button
    android:id="@+id/search_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/textView1"
    android:layout_toRightOf="@+id/textView1"
    android:text="@string/searchText"
    android:onClick="retrievePersonData"
     />

下面是 Main Activty java 文件中包含方法 retrievePersonData 的代码:

public class MainActivity extends Activity {
private static final String SERVICE_URL = "http://serverIP";
private static final String TAG = "MainActivity";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button btnOpenNewActivity = (Button) findViewById(R.id.search_button);
        btnOpenNewActivity .setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

        Intent myIntent = new Intent(MainActivity.this,PersonModel.class);

        MainActivity.this.startActivity(myIntent);

        }

        });
        }
        catch (Exception e)
        {

        }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}



public void handleResponse(String response) {
    EditText edFirstName = (EditText) findViewById(R.id.firstName);
    EditText edLastName = (EditText) findViewById(R.id.lastName);
    EditText edEmail = (EditText) findViewById(R.id.email);
    EditText edAddress = (EditText) findViewById(R.id.address);

    edFirstName.setText("");
    edLastName.setText("");
    edEmail.setText("");
    edAddress.setText("");

    try {
        JSONObject jso = new JSONObject(response);

        String firstName = jso.getString("firstName");
        String lastName = jso.getString("lastName");
        String email = jso.getString("email");
        String address = jso.getString("address");

        edFirstName.setText(firstName);
        edLastName.setText(lastName);
        edEmail.setText(email);
        edAddress.setText(address);

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);

    }
}

public void hideKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

public class WebServiceTask extends AsyncTask<String, Integer, String> {
    public static final int GET_TASK = 1;
    public static final int POST_TASK = 2;

    private static final String TAG = "WebServiceTask";

    // connection timeout in milliseconds.. waiting for connect
    private static final int CONN_TIMEOUT = 3000;

    // socket timeout, in milisecs (waiting for data)...
    private static final int SOCKET_TIMEOUT = 5000;

    private int taskType = GET_TASK;
    private Context mContext = null;
    private String processMessage = "Processing...";

    private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    private ProgressDialog pDlg = null;

    public WebServiceTask(int taskType, Context mContext, String processMessage) {
        this.taskType = taskType;
        this.mContext = mContext;
        this.processMessage = processMessage;

    }

    public void addNameValuePair(String name, String value) {
        params.add(new BasicNameValuePair(name, value));
    }

    private void showProgressDialog() {
        pDlg = new ProgressDialog(mContext);
        pDlg.setMessage(processMessage);
        pDlg.setProgressDrawable(mContext.getWallpaper());
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
        pDlg.setCancelable(false);
        pDlg.show();
    }

    @Override
    protected void onPreExecute() {

        hideKeyboard();
        showProgressDialog();

    }

    protected String doInBackground(String... urls) {
        String url = urls[0];
        String result = "";

        HttpResponse response = doResponse(url);

        if(response == null) {
            return result;
        } else {
            try {

                result = inputStreamToString(response.getEntity().getContent());

            } catch (IllegalStateException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);

            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }
        }

        return result;


    }

    @Override
    public void onPostExecute(String response) {

        handleResponse(response);
        pDlg.dismiss();

    }

    public HttpParams getHttpParams() {

        HttpParams httpa = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpa, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpa, SOCKET_TIMEOUT);

        return httpa;
    }

    public HttpResponse doResponse(String url) {

    HttpClient hClient = new DefaultHttpClient(getHttpParams());

    HttpResponse response = null;

    try {
        switch (taskType) {

        case POST_TASK:
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(params));
            response = hClient.execute(httppost);
            break;
        case GET_TASK:
            HttpGet httpget = new HttpGet(url);
            response = hClient.execute(httpget);
            break;
        }

    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }
    return response;
    }

    private String inputStreamToString(InputStream is) {

        String line = "";
        StringBuilder total = new StringBuilder();

        BufferedReader bf = new BufferedReader(new InputStreamReader(is));

        try {
            while ((line = bf.readLine()) != null) {
                total.append(line);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }
    return total.toString();
    }   


}

当我单击按钮时,它应该做两件事:

  1. 使用文本字段打开一个新活动。

  2. 使用来自 Web 服务项目的信息填充这些文本字段。

如果我有一个带有文本字段和按钮的活动(即,我单击它与 Web 服务对话并用信息填充字段),这工作得很好。在这种情况下,我单击按钮,它会打开新活动,但不会填充文本字段......它什么也不做。

有人可以帮忙吗,如果需要更清楚,我会的。任何帮助是极大的赞赏。

4

1 回答 1

1

您正在尝试在您的 UI 代码中运行 HTTP 请求,这就是您获得强制关闭的原因。请尝试在服务或 AysncTask 或线程中运行,这样 UI 线程不会被阻塞。

请参考这个例子

您可以在按钮单击中执行多个操作,触发 GET 方法如上述技术和 startActivity:

public class PersonModel extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EditText firstNameTxt= (EditText) findViewById(R.id.editText1);
        firstNameTxt.setText("set your value");
    }
}

尝试在 PersonModel 的 OnCreate 方法中使用 SetText 填充 EditText 的值。

谢谢

于 2013-01-11T22:45:39.707 回答