Reputation: 103
I'm making an Android application wherein a student logs in with his registration ID then can access services like view his grades, class schedule, etc. without entering his registration ID twice.
My question here is, how can I get the registration ID he first entered during login and use it to access other activities so that he would not have to enter again?
Here's is the code for the login activity:
package com.example.kreshiathea.myfirstapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity2 extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
String rfid = et.getText().toString().trim();
Intent in = new Intent(getApplicationContext(), MainActivity3Activity.class);
in.putExtra("rfid", rfid);
startActivity(in);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show( MainActivity2.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://usamobileapp.pe.hu/webservice/check.php"); // make sure the url is correct.
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText( MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent( MainActivity2.this, MainActivity3Activity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity2.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity2.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
I tried to uses an instance so I could import variable to another class. But I'm sure where to put it exactly so I placed it here:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
String rfid = et.getText().toString().trim();
Intent in = new Intent(getApplicationContext(), MainActivity3Activity.class);
in.putExtra("rfid", rfid);
startActivity(in);
This is the class where I want to import the variable MainActivity3Activity
Here's the code:
package com.example.kreshiathea.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity3Activity extends Activity {
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://usamobileapp.pe.hu/webservice/student_info.php");
try {
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", rfid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView result = (TextView) findViewById(R.id.tvResult);
try {
request = new HttpGet("http://usamobileapp.pe.hu/webservice/student_info.php");
response = httpclient.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I place the receiving intent here:
public class MainActivity3Activity extends Activity {
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;
The MainActivity3Activity
class also displays the student information (using the previously entered registration ID).
I'm not sure if I correctly used and placed the intents. So please I'm looking for any help.
Upvotes: 2
Views: 982
Reputation: 711
Intent intent = getIntent();
String id = intent.getStringExtra("regId");
Using this id you can get all the details in the next activity.
Upvotes: 1
Reputation: 536
You could store the registration as a static variable, which means it will maintain its value and you can access it from anywhere. I've done this loads of times in my own code and it's really handy.
For example, you could create a class called Globals or something, and in this class have your registration number.
public class Globals {
public static String registrationNumber;
// Or make a nice getter and setter for this :)
}
...so when you get the number from the user's input, set this variable:
Globals.registrationNumber = registrationNumber;
...then get it from this class when you need it later:
String registrationNumber = Globals.registrationNumber;
It's best to only use this for small things like this. If you keep massive objects in static variables, it means that object will continue to use memory throughout your app's lifecycle. Unless you are using something often, or the object is small (like your reg number), I wouldn't do this, as it is an unnecessary use of memory.
The other answers about passing the registration number between activities via the Intent is just as good an approach. It just means you have to write and read the value from the Intent extras every time. I would personally use that approach for passing an object or ID of something you have selected from a list to display it in a detail screen or something. For something that you regularly use, I'd go for the static variable approach.
Also... another thing you could do is save the registration number in the app preferences so that you can read it when the user starts the app and they don't have to log in again.
// Save the registration number to preferences.
SharedPreferences preferences = context.getSharedPreferences("MY_APP_PREFERENCES", Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("REGISTRATION_NUMBER", registrationNumber);
editor.commit();
...
// Get from preferences.
SharedPreferences preferences = context.getSharedPreferences("MY_APP_PREFERENCES", Context.MODE_PRIVATE);
String registrationNumber = preferences.getString("REGISTRATION_NUMBER", null);
// The second parameter above is the default value if nothing is returned.
Good luck!
Upvotes: 0
Reputation: 2757
Use sharedpreferences if you want to use in multiple activities
SharedPreferences preferences=getSharedPreferences("logindetails", Activity.MODE_PRIVATE);
Editor editor=preferences.edit();
editor.putString("regId", id);
editor.commit();
You can get regid as follows
id=getSharedPreferences("logindetails", Activity.MODE_PRIVATE).getString("regId",defaultValue);
Hope this will help you.
Upvotes: 2
Reputation: 132982
Call getIntent();
method to receive Intent from previous Activity in onCreate
method of MainActivity3Activity
Activity like :
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
}
Upvotes: 3
Reputation: 47817
You should move
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
inside onCreate(...)
method of Activity
getIntent()
is available only after onCreate(...)
you cant used it before onCreate(...)
Upvotes: 2