Android - 使用另一个类的变量?

时间:2015-02-25 09:29:50

标签: java android

我正在制作一个Android应用程序,其中学生使用他的注册ID登录,然后可以访问服务,例如查看他的成绩,课程安排等,而无需两次输入他的注册ID。

我的问题是,如何获取他在登录时首次输入的注册ID,并使用它来访问其他活动,以便他不必再次输入?

以下是登录活动的代码:

    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();
        }
    });
}
    }

我试图使用一个实例,所以我可以将变量导入另一个类。但我确定把它放在哪里,所以我把它放在这里:

 @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);

这是我要导入变量MainActivity3Activity

的类

以下是代码:

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();
    }
}

我将接收意图放在这里:

public class MainActivity3Activity extends Activity {

Intent in = getIntent();
String rfid = in.getStringExtra("rfid");


HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;

MainActivity3Activity课程还会显示学生信息(使用之前输入的注册ID)。

我不确定我是否正确使用并放置了意图。所以,我正在寻求任何帮助。

5 个答案:

答案 0 :(得分:3)

调用getIntent();方法,以onCreate活动的MainActivity3Activity方式接收上一个活动中的意图,如:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent in = getIntent();
   String rfid = in.getStringExtra("rfid");
}

答案 1 :(得分:2)

你应该移动

Intent in = getIntent();
String rfid = in.getStringExtra("rfid");

onCreate(...)

Activity方法内部

getIntent()仅在您onCreate(...)

之前无法使用onCreate(...)之后才可用

答案 2 :(得分:2)

如果要在多个活动中使用,请使用sharedpreferences

SharedPreferences preferences=getSharedPreferences("logindetails", Activity.MODE_PRIVATE);
Editor editor=preferences.edit();
editor.putString("regId", id);
editor.commit();

您可以按以下方式获得注册

id=getSharedPreferences("logindetails", Activity.MODE_PRIVATE).getString("regId",defaultValue);

希望这会对你有所帮助。

答案 3 :(得分:1)

Intent intent = getIntent();
String id = intent.getStringExtra("regId");

使用此ID可以获得下一个活动的所有详细信息。

答案 4 :(得分:0)

您可以将注册存储为静态变量,这意味着它将保持其值,您可以从任何地方访问它。我已经在我自己的代码中完成了这么多次,这非常方便。

例如,你可以创建一个名为Globals的类,或者在这个类中有你的注册号。

public class Globals {
    public static String registrationNumber;
    // Or make a nice getter and setter for this :)
}

...所以当你从用户的输入中得到数字时,设置这个变量:

Globals.registrationNumber = registrationNumber;

...然后在以后需要时从这个课程中获取它:

String registrationNumber = Globals.registrationNumber;

最好只将此用于此类小事。如果将大量对象保存在静态变量中,则意味着对象将在整个应用程序的生命周期中继续使用内存。除非你经常使用某些东西,或者对象很小(比如你的注册号),否则我不会这样做,因为它是不必要的内存使用。

关于通过Intent在活动之间传递注册号的其他答案也是一种很好的方法。它只是意味着你必须每次都从Intent extras中写入和读取值。我个人会使用这种方法传递您从列表中选择的对象或ID,以便在详细屏幕或其他内容中显示它。对于经常使用的东西,我会选择静态变量方法。

另外......您可以做的另一件事是将注册号码保存在应用程序首选项中,这样您就可以在用户启动应用程序时阅读它,而无需再次登录。

// 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.
祝你好运!