我试图根据服务器的响应显示消息但不知何故每次都失败。当我通过提供静态值从不同的项目中单独运行来自java类的相同代码时,它正在正常运行,我能够获得响应代码。请参考代码并帮我纠正错误。
MainActivity.java
public class MainActivity extends Activity implements OnClickListener,
Runnable {
Context context;
EditText editTextNum, editText, editUserName, editPassword;
Button btnsend;
ProgressDialog pd;
String gateway_name;
Thread t;
Spinner spinner1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
editUserName = (EditText) findViewById(R.id.edit_userName);
editPassword = (EditText) findViewById(R.id.edit_password);
editTextNum = (EditText) findViewById(R.id.edit_number);
editText = (EditText) findViewById(R.id.edit_message);
spinner1 = (Spinner) findViewById(R.id.SpinnerGateway);
btnsend = (Button) findViewById(R.id.btnsend);
btnsend.setOnClickListener(this);
}
/** Called when the user clicks the Send button */
public void sendMessage() {
String usrname = editUserName.getText().toString();
String usrPassword = editPassword.getText().toString();
String number = editTextNum.getText().toString();
String message = editText.getText().toString();
gateway_name = String.valueOf(spinner1.getSelectedItem());
String msgreciever = number;
String testMessage = message;
try {
SmsSender.sendMessage(msgreciever, testMessage, usrname,
usrPassword, gateway_name);
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "SMS Sending Failed.",
Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
settingmenuClicked();
return true;
case R.id.menu_help:
showHelp();
return true;
case R.id.menu_inbox:
showInbox();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public boolean isValid() {
if (editUserName.getText().length() == 10
&& editPassword.getText().length() != 0
&& editTextNum.getText().length() == 10
&& editText.getText().length() != 0) {
return true;
}
return false;
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == btnsend) {
if (!isOnline()) {
Toast.makeText(MainActivity.this,
"No Internet Access..Cannot Send SMS",
Toast.LENGTH_SHORT).show();
} else if (!isValid()) {
Toast.makeText(MainActivity.this,
"All fields are required. Try Again.",
Toast.LENGTH_SHORT).show();
} else {
pd = ProgressDialog.show(MainActivity.this, "Free Sms",
"Sending SMS..Please Wait..!!", true);
t = new Thread(this);
t.start();
}
}
}
public void settingmenuClicked() {
Toast.makeText(MainActivity.this, "Setting Menu Coming Soon",
Toast.LENGTH_SHORT).show();
}
public void showHelp() {
Toast.makeText(MainActivity.this, "Help Coming Soon",
Toast.LENGTH_SHORT).show();
}
public void showInbox() {
//Intent intent = new Intent(this, Inbox.class);
//startActivity(intent);
}
public void run() {
// TODO Auto-generated method stub
sendMessage();
mHandler.sendEmptyMessage(0);
}
public Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
pd.dismiss();
String response = SmsSender.responsecode;
if(response == "1"){
Toast.makeText(MainActivity.this, "Message Sent Successfully",Toast.LENGTH_SHORT).show();
} else if(response == "-1"){
Toast.makeText(MainActivity.this, "Server Error",Toast.LENGTH_SHORT).show();
} else if(response == "-2"){
Toast.makeText(MainActivity.this, "Invalid Username",Toast.LENGTH_SHORT).show();
} else if(response == "-3"){
Toast.makeText(MainActivity.this, "Invalid Message Text",Toast.LENGTH_SHORT).show();
} else if(response == "-4"){
Toast.makeText(MainActivity.this, "Login Failed",Toast.LENGTH_SHORT).show();
} else if(response == "-5"){
Toast.makeText(MainActivity.this, "IP is blocked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Unknown Error",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(MainActivity.this, "Message Sent To Server",
// Toast.LENGTH_SHORT).show();
editTextNum.setText("");
editText.setText("");
editTextNum.requestFocus();
}
};
}
SmsSender.java
public class SmsSender {
static final String _url = "http://ubaid.tk/sms/sms.aspx";
static final String charset = "UTF-8";
public static String responsecode = "0";
// to build the query string that will send the message
private static String buildRequestString(String targetPhoneNo,
String message, String userName, String Password, String Gateway) throws UnsupportedEncodingException {
String[] params = new String[5];
params[0] = userName;
params[1] = Password;
params[2] = message;
params[3] = targetPhoneNo;
params[4] = Gateway;
String query = String.format(
"uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
URLEncoder.encode(params[0], charset),
URLEncoder.encode(params[1], charset),
URLEncoder.encode(params[2], charset),
URLEncoder.encode(params[3], charset),
URLEncoder.encode(params[4], charset));
return query;
}
public static void sendMessage(String reciever, String message, String userName, String password, String Gateway)
throws Exception {
// To establish the connection and perform the post request
URLConnection connection = new URL(_url + "?"
+ buildRequestString(reciever, message, userName, password, Gateway)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
// This automatically fires the request and we can use it to determine
// the response status
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
System.out.println(br.readLine());
responsecode = br.readLine();
}
public static void main(String[] args) throws Exception {
// To DO
//String testPhoneNo = "9876543210";
//String testMessage = "Sending Messages From java is not too hard";
//sendMessage(testPhoneNo, testMessage);
}
}
答案 0 :(得分:0)
我认为你是来自the example的过多复制和粘贴的受害者。我怀疑你得到了回应(否则你会遇到异常)。那你只是throwing it away to a System.out.println()。然后当你去设置responsecode
readLine()时返回null。
我试图为自己测试它,但我不能在印度之外使用API。