我想从php
获取变量的内容到android并使用Toast类显示它。我编写了以下代码,如果一个或两个字段为空,register.php
文件打印$isEmpty
,我的java代码应该获得$isEmpty
变量和if(text == "isEmpty")
的内容为结果Toast类应显示R.string.empty
。但是我使用以下代码的程序无法使用Toast类显示R.string.empty
。
public class MainActivity extends Activity {
EditText username, password;
Button register;
String name, pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.editText);
password= (EditText) findViewById(R.id.editText2);
register= (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
// CALL GetText method to make post method call
GetText();
}
catch(Exception ex)
{
}
}
});
}
public void GetText() throws UnsupportedEncodingException
{
// Get user defined values
name = username.getText().toString();
pass = password.getText().toString();
// Create data variable for sent values to server
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(name, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode(pass, "UTF-8");
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://127.0.0.1:8080/apps/register.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
if(text == "isEmpty")
{ String isEmpty = (String)getText(R.string.empty);
Toast.makeText(getApplicationContext(), isEmpty, Toast.LENGTH_LONG).show(); }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}
和
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = urldecode($_POST['username']);
$login = urldecode($_POST['login']);
if(empty($username) || empty($login)) {
$isEmpty = "isEmpty";
print "$isEmpty";
}
}?>
答案 0 :(得分:1)
使用
if(text == "isEmpty")
不正确
你必须使用
Java中的 if(text.equals("isEmpty"))