gpt4 book ai didi

php - 为什么 getdata 函数对主要 Activity 起作用?

转载 作者:太空狗 更新时间:2023-10-29 13:18:20 25 4
gpt4 key购买 nike

我是 android 开发的新手,目前我正在将数据发布和获取到 php 文件。我无法找到为什么 getData() 函数在主要 Activity 中不起作用,但它在另一个 Activity 中正常工作。我将相同的功能从仪表板 Activity 复制到主要 Activity 。

这是我的主要 Activity 代码

public class MainActivity extends ActionBarActivity {

private static final String TAG = "MainActivity.java";
private EditText editEmail;
private EditText editPass;
TextView resultView;

@Override
protected void onCreate(Bundle savedInstanceState) {
final Button loginButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.result);
getData();
editEmail = (EditText) findViewById(R.id.userEmail);
editPass = (EditText) findViewById(R.id.userPassword);
loginButton = (Button) findViewById(R.id.buttonlogin);
loginButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
//perform action
if (!isValidEmail(email)) {
editEmail.setError("Please enter valid Email...");
}
else if (!isValidPassword(pass)) {
editPass.setError("Please enter valid Password");
}else{
new PostDataAsyncTask().execute();

startActivity(new Intent(MainActivity.this, DashboardActivity.class));
}

//if (emailEditText.getText().toString().trim().length()==0) {
//Toast.makeText(getBaseContext(), "Email is empty!!!", Toast.LENGTH_SHORT).show();
//return;
// }else{
// Redirect to Another Activity
//startActivity(new Intent(MainActivity.this, DashboardActivity.class));
// }
//if(upassword.getText().toString().trim().length()==0){
// Toast.makeText(getBaseContext(), "Password is empty!!!", Toast.LENGTH_SHORT).show();
//return;
//}

}
});



}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
private boolean isValidPassword(String pass) {
if (pass != null && pass.length() > 10) {
return true;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}


public class PostDataAsyncTask extends AsyncTask<String, String, String> {

protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}

@Override
protected String doInBackground(String... strings) {
try {

// 1 = post text data, 2 = post file
int actionChoice = 2;

// post a text data
if(actionChoice==1){
postText();
}

} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}

// this will post our text data
private void postText(){
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
try{
// url where the data will be posted
String postReceiverUrl = "http://xyzweb.com/appservice.php";
Log.v(TAG, "postURL: " + postReceiverUrl);

// HttpClient
HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);

// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("first_name", email));
//nameValuePairs.add(new BasicNameValuePair("lastname", pass));


httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {

String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);

// you can add an if statement here and do other actions based on the response
}

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xyzweb.com/appservice.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();

result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}

//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);

for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("first_name")+"\n\n";
}

resultView.setText(s);

} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}

}
}

getData() 函数给出此错误 Couldnt connect to database

PHP代码

$name   = urldecode($_POST['first_name']);
//$user = urldecode($_POST['user']);
//$email = urldecode($_POST['email']);
//$pass = urldecode($_POST['pass']);
$postdata = array();
$postdata[]['first_name'] = 'hjgjh';
print(json_encode($postdata));

最佳答案

getData() 函数执行远程 URL。这些类型的请求应该由后台线程而不是主线程处理。这可以像这样完成:

   @Override
protected void onCreate(Bundle savedInstanceState) {
final Button loginButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.result);
//Call your getData function from AsyncTask
new YourAsyncTask.execute();
...
}

public class YourAsyncTask extends AsyncTask<String, String, String> {

protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(String... strings) {
//Call getData function from here
getData();
return null;
}

@Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}

关于php - 为什么 getdata 函数对主要 Activity 起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32066000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com