0

サーバーからの応答に基づいてメッセージを表示しようとしていますが、どういうわけか毎回失敗します。静的な値を提供することにより、別のプロジェクトとは別に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);
}

 }
4

1 に答える 1

0

あなたは例からのコピーと貼り付けの犠牲者だと思います。応答が得られていると思われます (応答がない場合、例外が発生します)。あなたはそれをSystem.out.println() に捨てているだけです。次に、set responsecode readLine()に移動すると、 null が返されます。

自分でテストしようとしましたが、インド以外では API を使用できません。

于 2012-09-04T18:18:15.797 に答える