无法通过getIntent()将第一个活动的textview值传递给第二个活动的textview

时间:2015-10-09 09:40:27

标签: java android android-intent textview

我试图在不同的活动之间传递textview值,这是我尝试过的代码:

LoginActivity.java

    public class LoginActivity extends Activity {

Button btnLogin;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnLogin = (Button) findViewById(R.id.btnLogin);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Session manager
    session = new SessionManager(getApplicationContext());



    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, SliderMenu.class);
        startActivity(intent);
        finish();
    }

    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            // Check for empty data in the form
            if (!email.isEmpty() && !password.isEmpty()) {
                // login user
                checkLogin(email, password);
                // Prompt user to enter credentials
                Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
            }
        }

    });

}

/**
 * function to verify login details in mysql db
 * */
private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    pDialog.setMessage("Logging in ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST, Urls.URL_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
     //Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {

                    // user successfully logged in
                    // Create login session
                    session.setLogin(true);

                    // Now store the user in SQLite
                    String uid = jObj.getString("admin_id");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String password = user.getString("password");

                    //Log.v("level--", jObj.getString("level"));
                    TextView textView = (TextView) findViewById(R.id.value);
                    textView.setText(jObj.getJSONObject("user").getString("level"));

                    int a = Integer.parseInt(textView.getText().toString());
                    Intent i = new Intent(LoginActivity.this, StudentActivity.class);
                    Bundle b=new Bundle();
                    b.putInt("level", a);
                    i.putExtras(b);
                    startActivity(i);
                    Intent ii = new Intent(LoginActivity.this, StudentActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("level", a);
                    startActivity(ii.putExtras(bundle));

                    // Inserting row in users table
                    db.addUser(name, email, password);

                    Intent intent = new Intent(LoginActivity.this, SliderMenu.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", email);
            params.put("password", password);

            return params;
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

@Override
protected void onResume() {
    super.onResume();

}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}

StudentActivity.java

    public class StudentActivity extends ListActivity {

private ProgressDialog pDialog;

// JSON Node names
private static final String TAG_STUDENT = "result";
private static final String TAG_GR_NUM = "gr_num";
private static final String TAG_NAME = "name";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_student);
    TextView textView = (TextView) findViewById(R.id.textView);

        textView.setText(Integer.toString(getIntent().getExtras().getInt("level")));;

    String a = getIntent().getStringExtra("level");
    textView.setText(a);

    studentList = new ArrayList<HashMap<String, String>>();
    new GetStudents().execute();
}
/**
 * Async task class to get json by making HTTP call
 * */
private class GetStudents extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(StudentActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall("http://10.0.2.2/android_login_api/fetchdata.php", ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_STUDENT);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    // Phone node is JSON Object
                    //JSONObject phone = c.getJSONObject(TAG_PHONE);
                    String gr_num = c.getString(TAG_GR_NUM);
                    String name = c.getString(TAG_NAME);

                    // tmp hashmap for single contact
                    HashMap<String, String> studnt = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    studnt.put(TAG_GR_NUM, gr_num);
                    studnt.put(TAG_NAME, name);

                    // adding contact to contact list
                    studentList.add(studnt);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                StudentActivity.this, studentList, R.layout.list_items, new String[] { TAG_GR_NUM, TAG_NAME },
                new int[] {  R.id.gr_num ,R.id.name });
        setListAdapter(adapter);
    }
}
 }

我不知道代码有什么问题,但是日志显示在LoginActivity中字符串a获取textview值,但StudentActivity String a没有从以前的活动中获取值..任何帮助都会得到真正的赞赏......

更新:最后我只是更改了我的代码,用于将值从getIntent()方法传递到共享首选项,现在它的传递数据就像魅力:) Here是链接..

4 个答案:

答案 0 :(得分:0)

尝试使用getExtras()....

    Bundle i = getIntent().getExtras();
    String a = i.getStringExtra("level");
    Log.d("TAG1", String.valueOf(a));
    textView.setText(String.valueOf(a));

答案 1 :(得分:0)

 String a = getIntent().getExtras().getString("level");
 textView.setText(String.valueOf(a));

答案 2 :(得分:0)

活动1:

 Intent ii = new Intent(this, ShareOnFacebook.class);
Bundle bundle=new Bundle();
bundle.putString("message", facebookMessage);
startActivity(ii.putExtras(bundle))

Activity2:
String facebookMessage = getIntent().getStringExtra("message"); 
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);    
txtView.setText(message);

答案 3 :(得分:0)

您正在意图中传递包并额外检索意图。要么传递bundle并检索bundle,要么传递intent并检索它们。 在您调用StudentActivity的代码中尝试下面的代码。即

  Intent ii = new Intent(LoginActivity.this, StudentActivity.class);
  ii.putExtra("level", a);         
  startActivity(ii);