私はメインアクティビティで非同期タスククラスを呼び出しています:ここにコードがあります
public class MainActivity extends Activity implements AsyncResponse {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connection connection=new Connection();
connection.execute();
}
Here is my Connection class:
class Connection extends AsyncTask<String,String, Void>
{
public AsyncResponse delegate=null;
String result = "";
InputStream is=null;
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
/*ArrayList<NameValuePair> nameValuePairs = null;
int i=0;
String username=params[i].toString();
String password=params[i+1].toString();
String validation=params[i+2].toString();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
// nameValuePairs.add(new BasicNameValuePair("username",));*/
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/connection.php");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
// TODO Auto-generated method stub
}
protected void onPostExecute(Void v) {
try{
JSONArray jArray = new JSONArray(result);
delegate.processFinish(jArray);
// labels2.add(password);
//Returndata(labels2);
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
実行後、Jarrayをインターフェイスに送信します。メインのアクティビティでそのインターフェイスを使用します。インターフェイスは次のとおりです。
public interface AsyncResponse {
void processFinish(JSONArray jArray);
}
そして、このような主な活動を使用します:
@Override
public void processFinish(JSONArray jarray) {
// TODO Auto-generated method stub
try {
for(int i=0;i<=jarray.length();i++)
{
JSONObject json_data;
json_data = jarray.getJSONObject(i);
String username=json_data.getString("username");
String password=json_data.getString("password");
Toast.makeText(getBaseContext(),username+password,Toast.LENGTH_LONG).show();
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}