我正在创建一个能够使用HTTP DELETE从JSON中删除数据的Android应用程序。但是我遇到了问题。我创建了2个不同的文件。 MainActivity和Async中的其中一个。
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
onClickButtonListner();
}
public void onClickButtonListner() {
final Button btn = (Button) findViewById(R.id.delete_btn);
final String URL = myurl;
btnDelete.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Async asyn = new Async(URL);
asyn.execute();
}
});
}
}
Async.java
public class Async extends AsyncTask<Void, Void, String> {
String murl;
public Async(String url) {
murl = url;
}
@Override
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection;
URL url ;
try {
final EditText id= (EditText)findViewById(R.id.delete_id);
**showing unable to resolve method findViewById**
String delete_url = murl + "/" + id.getText().toString();
url = new URL(delete_url);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
所以我的问题是我的Async类显示无法找到findViewById方法。
所以请帮我解决这个问题 谢谢
答案 0 :(得分:1)
尝试更改您的代码,如下所示:
<强> MainActivity.java 强>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
onClickButtonListner();
}
public void onClickButtonListner() {
final Button btn = (Button) findViewById(R.id.delete_btn);
final String URL = myurl;
final EditText id= (EditText)findViewById(R.id.delete_id);
btnDelete.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Async asyn = new Async(URL,id.getText().toString());
asyn.execute();
}
});
}
}
<强> Async.java 强>
public class Async extends AsyncTask<Void, Void, String> {
String murl,id;
public Async(String url,String _id) {
murl = url;
id=_id;
}
@Override
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection;
URL url ;
try {
String delete_url = murl + "/" + id;
url = new URL(delete_url);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}