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

标签 java android

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

我的问题是,如何才能得到他在登录时第一次输入的注册ID,并用它来访问其他 Activity ,这样他就不用再输入了?

这是登录 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();
        }
    });
}
    }

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

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

我把接收 Intent 放在这里:

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)。

我不确定我是否正确使用和放置了 Intent 。所以我正在寻求任何帮助。

最佳答案

MainActivity3Activity Activity 的 onCreate 方法中调用 getIntent(); 方法接收上一个 Activity 的 Intent,例如:

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

关于java - Android - 使用另一个类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715398/

相关文章:

android - 在 ListView 上长按停止单击操作

Android Timber 多次记录

android - 将 IntelliJ 与 Android 插件一起使用,而不是使用 Android Studio

android - 如何使汉堡菜单完全可见

java - Tensorflow Android 演示 : load a custom graph in?

java - 无法让 charAt(0) 工作

java - Java 中的泛型类型推断

java - 如何使用spring jdbc在mysql中插入外键

java - handler.sendMessage() 未到达 android 中的handleMessage()

android - 按下 4 时 EditText 打印 $