Java 无法通过getIntent()将第一个活动的textview值传递给第二个活动的textview
我正在尝试在不同的活动之间传递textview值,下面是我尝试过的代码: LoginActivity.javaJava 无法通过getIntent()将第一个活动的textview值传递给第二个活动的textview,java,android,android-intent,textview,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; p
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();
}
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);
}
}
}
StudentActivity.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();
}
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字符串a没有从以前的活动中获取值。。任何帮助都将得到真诚的感谢
更新:最后,我只是更改了将值从getIntent方法传递到共享首选项的代码,现在它像一个符咒一样传递数据:是链接..尝试使用getExtras
Bundle i = getIntent().getExtras();
String a = i.getStringExtra("level");
Log.d("TAG1", String.valueOf(a));
textView.setText(String.valueOf(a));
活动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);
您将在intent中传递bundle并检索intent extra。要么传递bundle并检索bundle,要么传递intentextra并检索相同的bundle。 在您的代码中调用StudentActivity时,请尝试下面的代码。i、 e
Intent ii = new Intent(LoginActivity.this, StudentActivity.class);
ii.putExtra("level", a);
startActivity(ii);
何时调用此getIntent方法?在StudentActivity.java的onCreate方法上,不需要使用String.valueOf。试试文本视图。setTexta@DavidWasser是的,我知道它可以与String.valueOf一起使用,但是em只是获取它所具有的值。你能发布StudentActivity的onCreate方法吗?它正在将意图更改为Bundle,em只是尝试获取意图,而不是使用Bundle。此代码已被破坏。另外,使用getExtras与OP已经在做的事情没有什么不同。您的代码在第2行的getStringExtras方法上抛出错误这与OP已经在做的事情没有任何不同。getStringExtra执行与getExtras.getString.check ifa完全相同的操作!=null{textView.setTextString.valueOfa;}请重试this@Princesa如果您的textview值字符串正确,您应该直接传递字符串而不是此字符串a=textview.getText.toString;将文本设置为文本视图jObj.getJSONObjectuser.getStringlevel时;检查您是否获得了一些值或为空。或者只需通过传递硬代码值来检查它从mysql解析我的json值。。我的登录活动也不会获取该值,只是不会将其传递给另一个活动