I am trying to pass textview value between different activities, here is my code that i've tried:
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);
}
}
}
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...
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..
Activity 1:
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
Try using getExtras()....