SetText用于EditText

时间:2015-04-06 22:23:36

标签: java android eclipse android-layout android-edittext

我正在创建一个更新配置文件页面,在从数据库获取数据后,我想在edittexts中设置值,以便我可以编辑它们。当我尝试它时,它给了我错误。请告诉我该怎么做。谢谢!

这是我的ProfileActivity.java类

package com.example.fproject;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ProfileActivity extends Activity {

EditText firstnameBox, lastnameBox, departmentBox, officeBox, emailBox, phonenoBox, passwordBox, statusBox, confirm_passwordBox;
private Button register;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private ProgressDialog pDialog;
String user;
SessionManagement session;
GetIPAddress getIPaddress = new GetIPAddress();
private static String url_get_user_data;    // products JSONArray
JSONArray data = null;


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

    session = new SessionManagement(getApplicationContext()); 
    SharedPreferences sp = getSharedPreferences("login_pref", 0);
    user = sp.getString(session.KEY_EMAIL, null);

    url_get_user_data = getIPaddress.getIP()+"get_user_data_for_profile.php";

    firstnameBox = (EditText)findViewById(R.id.update_firstname);
    lastnameBox = (EditText)findViewById(R.id.update_lastname);
    departmentBox = (EditText)findViewById(R.id.update_department);
    officeBox = (EditText)findViewById(R.id.update_office);
    emailBox = (EditText)findViewById(R.id.update_email);
    phonenoBox = (EditText)findViewById(R.id.update_phoneno);
    passwordBox = (EditText)findViewById(R.id.update_password);
    confirm_passwordBox = (EditText)findViewById(R.id.update_confirm_password);
    new GetUserData().execute();
    register = (Button)findViewById(R.id.update_register); 
    register.setOnClickListener(new OnClickListener() {

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

        }

    });

   }

class GetUserData extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... arg0) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", user));
        // getting JSON string from URL
        JSONObject json = jsonParser.makeHttpRequest(url_get_user_data, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("User Data: ", json.toString());

        try {
            // Checking for SUCCESS TAGh
            int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully received product details
                    JSONArray userObj = json
                            .getJSONArray("data"); // JSON Array

                    // get first product object from JSON Array
                    JSONObject user = userObj.getJSONObject(0);             


                    //firstnameBox.setText(user.getString("firstname"));
                    firstnameBox.setText("lsdf;skdjf", TextView.BufferType.EDITABLE);
                    /*lastnameBox.setText(user.getString("lastname"));
                    departmentBox.setText(user.getString("department"));
                    officeBox.setText(user.getString("office"));
                    emailBox.setText(user.getString("email"));
                    phonenoBox.setText(user.getString("phoneno"));
                    passwordBox.setText(user.getString("password"));
                    statusBox.setText(user.getString("status"));
*/

            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        AdminHomeActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }}


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

}

这是Logcat错误

 04-06 22:31:25.725: E/AndroidRuntime(644): FATAL EXCEPTION: AsyncTask #1
 04-06 22:31:25.725: E/AndroidRuntime(644): java.lang.RuntimeException: An error occured while executing doInBackground()
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.os.AsyncTask$3.done(AsyncTask.java:266)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.lang.Thread.run(Thread.java:1020)
 04-06 22:31:25.725: E/AndroidRuntime(644): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewRoot.checkThread(ViewRoot.java:3392)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewRoot.invalidateChild(ViewRoot.java:597)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:645)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:3691)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.view.View.invalidate(View.java:7141)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.invalidateCursor(TextView.java:3866)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.spanChange(TextView.java:6932)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:7058)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:918)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:615)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:518)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.Selection.setSelection(Selection.java:74)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.Selection.setSelection(Selection.java:85)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:288)  
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.setText(TextView.java:2814)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.TextView.setText(TextView.java:2691)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.widget.EditText.setText(EditText.java:78)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at com.example.fproject.ProfileActivity$GetUserData.doInBackground(ProfileActivity.java:100)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at com.example.fproject.ProfileActivity$GetUserData.doInBackground(ProfileActivity.java:1)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at android.os.AsyncTask$2.call(AsyncTask.java:252)
 04-06 22:31:25.725: E/AndroidRuntime(644):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 04-06 22:31:25.725: E/AndroidRuntime(644):     ... 4 more

谢谢!..请告诉我该怎么做

2 个答案:

答案 0 :(得分:0)

您正尝试从不允许的后台线程更改UI。您应该覆盖AsyncTask的onPostExecute并使用它来更新UI。您的AsyncTask应如下所示:

    class GetUserData extends AsyncTask<String, String, JSONObject> {

         @Override
         protected JSONObject doInBackground(String... arg0) {
              //Code to get user
              return user;
         }

         @Override
         protected void onPostExecute(JSONObject user) {
             try {
                firstnameBox.setText(user.getString("firstname"));
             } catch (Exception e) {}

         }
     }

答案 1 :(得分:0)

您正在尝试从AsyncTask的doInBackground()更改UI,但是在后台线程上运行,而不是在主线程(或UI线程)上运行。这就是onPostExecute()的用途,因为AsyncTask使得它在doInBackground完成后立即在UI线程上运行。

我的建议:

  1. 将AsyncTask类的结果类型更改为JSONObject:

    class GetUserData extends AsyncTask<String, String, JSONObject> {

  2. 将doInBackground()的返回类型更改为JSONObject:

    protected JSONObject doInBackground(String... arg0) {

  3. 返回JSONObject对象user,并删除您注释掉的所有与UI相关的代码,并删除第100行

    JSONObject user = userObj.getJSONObject(0); return user;

  4. 将与UI相关的代码放在onPostExecute()
  5. 的新方法中

    `@Override protected void onPostExecute(JSONObject用户){     if(user == null){         返回; // 无计可施     }

    try {
        firstnameBox.setText(user.getString("firstname"));
        lastnameBox.setText(user.getString("lastname"));
        departmentBox.setText(user.getString("department"));
        officeBox.setText(user.getString("office"));
        emailBox.setText(user.getString("email"));
        phonenoBox.setText(user.getString("phoneno"));
        passwordBox.setText(user.getString("password"));
        statusBox.setText(user.getString("status"));
    } catch(JSONException e) {
      // process your exception
    }
    

    } `