将字符串值从活动类传递到非活动类

时间:2017-07-17 06:59:33

标签: java android string android-activity

我是android中的新手,我试图将TextView中的字符串传递给没有活动的Client.java类。 我实际上是想在MainActivity中做到这一点:

    Intent i = new Intent(MainActivity.this, Client.class);
    i.putExtra("STRING_I_NEED", String.valueOf(indr));

在客户端:

Context context;
Intent intent = ((Activity) context).getIntent();
static Bundle getIp = getIntent.getExtra("STRING_I_NEED");
public static final Bundle SERVERIP = getIp; 

但那句话"

  

无法解析符号" getIntent"在字符串中     static Bundle getIp = getIntent.getExtra(" STRING_I_NEED");

客户代码:

public class Client {
private static String mIP= "";
private String serverMessage;
public static final String SERVERIP = mIP;
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;

PrintWriter out;
BufferedReader in;


public void setIp(String _IP) {
    mIP = _IP;
}
public Client(OnMessageReceived listener) {
    mMessageListener = listener;
}


public void sendMessage(String message){
    if (out != null && !out.checkError()) {
        out.println(message);
        out.flush();
    }
}

public void stopClient(){
    mRun = false;
}

public void run() {

    mRun = true;

    try {
        InetAddress serverAddr = InetAddress.getByName(String.valueOf(SERVERIP));

        Log.e("TCP Client", "C: Connecting...");

        Socket socket = new Socket(serverAddr, SERVERPORT);

        try {

            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            Log.e("TCP Client", "C: Sent.");

            Log.e("TCP Client", "C: Done.");

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while (mRun) {
                serverMessage = in.readLine();

                if (serverMessage != null && mMessageListener != null) {
                    mMessageListener.messageReceived(serverMessage);
                }
                serverMessage = null;

            }

            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {

            socket.close();
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}


public interface OnMessageReceived {
    void messageReceived(String message);
}
}

这是MainActivity:

public class MainActivity extends AppCompatActivity {
Server server;
Client client;
public static String message,ippi;
public static TextView terminale,indr,msg;
TextView log;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
            "Via Beniamino Disraeli, 17,\n" +
            "42124 Reggio Emilia \n" +
            "Telefono: 0522 / 38 32 22 \n" +
            "Fax: 0522 / 38 32 72 \n" +
            "Partita IVA, Codice Fiscale \n" +
            "Reg. Impr. di RE 00168780351 \n" +
            "Cap. soc. € 50.000,00 i.v. \n" +  "" +
            "REA n. RE-107440 \n" +
            "presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings,helps,allerts,home;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Utils.darkenStatusBar(this, R.color.colorAccent);
    server = new Server(this);
    myDB = DataBaseHandler.getInstance(this);
    new connectTask().execute("");

    msg = (TextView) findViewById(R.id.msg);
    log = (TextView) findViewById(R.id.log_avviso);
    settings = (ImageButton) findViewById(R.id.impo);
    helps = (ImageButton) findViewById(R.id.aiut);
    allerts = (ImageButton) findViewById(R.id.msge);
    home = (ImageButton) findViewById(R.id.gab);
    terminale = (TextView) findViewById(R.id.terminal);
    indr = (TextView) findViewById(R.id.indr);

    Cursor cursor = myDB.fetchData();
    if(cursor.moveToFirst()){
        do {
            indr.setText(cursor.getString(1));
            terminale.setText(cursor.getString(2));
        }while(cursor.moveToNext());
    }


    client.setIp(indr.getText().toString());


    cursor.close();
    server.Parti();



    message = indr.getText().toString();

    if (client != null) {
        client.sendMessage(message);
    }

    home.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View view) {
                                    Toast.makeText(MainActivity.this,Client.SERVERIP, Toast.LENGTH_LONG).show();
                                }
                            });

    settings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
            startActivity(impostazioni);
        }
    });

    helps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent pgHelp = new Intent(getApplicationContext(), help.class);
            startActivity(pgHelp);
        }
    });

    allerts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Server.count = 0;
            SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            editor.apply();
            msg.setVisibility(View.INVISIBLE);
            Intent pgAlert = new Intent(getApplicationContext(), allert.class);
            startActivity(pgAlert);
        }
    });

}

public class connectTask extends AsyncTask<String,String,Client> {

    @Override
    protected Client doInBackground(String... message) {

        //we create a TCPClient object and
        client = new Client(new Client.OnMessageReceived() {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {
                //this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        client.run();

        return null;
    }

}
@Override
protected void onDestroy() {

    super.onDestroy();
    server.onDestroy();
}

}

5 个答案:

答案 0 :(得分:2)

<强>问题:

由于Client.java(根据您)不是活动类型类,因此您无法使用Client.java来调用/调用IntentIntent仅用于调用:ActivitiesBroadcastReceiverServices

您的Client.java不会扩展活动,广播或服务。这就是为什么你没有getIntent()函数,甚至函数onCreate()onReceive(), onStartCommand()or onHandleIntent()&#39; “就此而言。

正确的方式:

1。所以你需要做的就是像任何其他对象一样创建该类的对象并调用它的setter。您可以在类中定义公共方法以设置IP的值:

YourClass {
   private String mIP;

   public void setIp(String _IP) {
       mIp = _IP;
    }
}

在MainActivity类中,您可以在初始化对象后调用该方法:

MyClassObject.setIp("127.0.0.1");

2。定义重载的构造函数,并使用它设置值。

3。public static String IP中创建MainActivity,为其指定值,然后在您的课程中执行此操作以检索值:

YourClass {
       private String mIP;

       public void getIp() {
           mIP = MainActivity.IP;
        }
    }

答案 1 :(得分:1)

在您的客户端类中。

public void setString(String yourString){
    variableToStoreStringInClass = yourString;
}

在您的MainActivity中,您希望将字符串发送到客户端。

Client yourClient = new Client();
yourClient.setString("Enter the string");

或者您可以使用静态方法:

在客户端类中:

public static void setString(String yourString){
    variableToStoreStringInClass = yourString;
}

并在您的MainActivity中

Client.setString("Enter the string");

答案 2 :(得分:1)

在您设置活动时,在TextView中设置字符串时,也将其保存在共享首选项中,如下所示:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

prefs.edit().putString("IP", IP_String).apply();

然后在主要活动中:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

String ip = prefs.getString("IP", "AnyDefaultValue");

client.setIp(ip);

答案 3 :(得分:0)

在MainActivity中初始化静态字符串,并将textView文本分配给该字符串。

在Client.java中调用此MainActivity.IntializedString

答案 4 :(得分:0)

尝试以下示例

DISSMISS