package demo.chv.bhudev.chvlogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
TextView content;
EditText login, pass;
String Login, Pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (EditText)findViewById(R.id.txt_box_usr);
pass = (EditText)findViewById(R.id.txt_box_pwd);
content = (TextView)findViewById(R.id.txt_content);
Button save = (Button)findViewById(R.id.btn_login);
save.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v)
{
try{
// CALL GetText method to make post method call
GetText();
}
catch(Exception ex)
{
content.setText(ex.getMessage());
}
}
});
}
private void GetText() throws UnsupportedEncodingException{
Login = login.getText().toString();
Pass = pass.getText().toString();
Toast.makeText(this,"Started",Toast.LENGTH_LONG).show();
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(Login, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode(Pass, "UTF-8");
String text = "";
try{
URL url = new URL("mylink");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((text = reader.readLine()) != null){
sb.append(text);
break;
}
content.setText(sb);
}catch(Exception r) { Toast.makeText(this,r.getMessage().toString(),Toast.LENGTH_LONG).show();
}
}
}
對於上面的代碼,我收到異常「嘗試調用空對象引用上的虛擬方法'java.lang.String java.lang.toString()'
」。Android:發送/接收數據
我試過/在網上搜索很多東西,但無法找到解決方案。
對wh ich線你得到這個異常? – Lokesh
請添加您的完整活動代碼。 –
也粘貼你的logcat – Lokesh