こんにちは私はAndroidプログラミングに不慣れで、ネットワーク接続を確立するためにAsyncTaskを使用するようにアドバイスされました。doInBackgroundに追加する前に機能していた領域でエラーが発生します。
(例は解決できません)-キャッチセクション
およびonPostExecute:
トークン")"の構文エラー、; 期待される-(文字列結果)
(Toast型のメソッドmakeText(Context、CharSequence、int)は、引数(LongOperation、String、int)には適用されません)-Toast.makeTextの場合
これらのエラーは、コードを配置した場所と関係がありますか?私のコードを適応させる答えを歓迎します。
package com.example.clearlight;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URL;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.StrictMode;
import android.util.Log;
public class MainActivity extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.relative);
class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
URL url = null;
DefaultHttpClient httpclient = null;
try {
String registrationUrl = "http://10.0.2.2/SensorInfo/GetLightData?sensor=light";
url = new URL(registrationUrl);
HttpGet getRequest = new HttpGet(registrationUrl);
ResponseHandler<String> handler = new BasicResponseHandler();
httpclient = new DefaultHttpClient();
// request data from server
String result = httpclient.execute(getRequest, handler);
Log.d("MyApp", "Data from server is "+ result);}
catch (Exception ex) {Log.e("error",ex.toString());
ex.printStackTrace();
}
@Override
protected void onPostExecute(String result)
{
TextView text1 = (TextView) findViewById(R.id.text);
//Sets the new text to TextView (runtime click event)//*******
text1.setText("Light Data= " + result);
Toast.makeText(this, "Light Data:" + result, Toast.LENGTH_SHORT).show(); //MESSAGE BOX
//txtMessage.setText(String.valueOf(msg1) + " " + String.valueOf(msg2));
}
}
}
}
}