无法通过getIntent传递活动1的TextView的价值,第二个活动的TextView的() [英] Unable to pass 1st activity's textview value to 2nd activity's textview through getIntent()
问题描述
我试图通过不同活动之间TextView的价值,这是我的code,我试过:
I am trying to pass textview value between different activities, here is my code that i've tried:
LoginActivity.java
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
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);
}
}
}
我不知道什么是错用code,但日志中显示,在LoginActivity字符串一个越来越TextView的价值,但StudentActivity字符串一个没有得到从previous活性值..任何帮助将是忠实地$ AP p $ pciated ...
I dont know whats wrong with code but log is showing that in LoginActivity String a is getting textview value, but StudentActivity String a is not getting value from previous activity.. Any help would be truely appreciated...
更新:最后我只是改变我的code从getIntent()方法,传递价值,共享preferences,就像一个魅力:) <一个现在它传递数据href=\"http://stackoverflow.com/questions/21055702/how-to-pass-extra-intent-to-two-activities\">Here是链接..
Updated: Finally i just change my code for passing value from getIntent() method to shared preferences, now its passing data like a charm :) Here is the link..
推荐答案
您传递包中的意图和检索意图额外费用。无论你通过捆绑和检索软件包或通过额外的意图和检索相同。
在您code,而调用StudentActivity尝试以下code。即
you are passing bundle in the intent and retrieving intent extra. Either you pass bundle and retrieve bundle or pass intent extra and retrieve the same. In you code while calling the StudentActivity try below code. i.e
Intent ii = new Intent(LoginActivity.this, StudentActivity.class);
ii.putExtra("level", a);
startActivity(ii);
这篇关于无法通过getIntent传递活动1的TextView的价值,第二个活动的TextView的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!