解決方法,我要創建一個ArrayAdapter,但是當我把getActivity()到構造它說cannot resolve method getActivity()
getActivity不能從片段
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import java.net.HttpURLConnection;
import java.lang.Void;
import android.widget.ListView;
import android.os.AsyncTask;
import android.content.Context;
public class HttpURLConnectionExample extends AsyncTask<ListView, Void, String> {
public ListView myList = null;
public void sendGet(ListView lv){
myList = lv;
this.execute();
return;
}
@Override
protected String doInBackground(ListView... arg0) {
String url = "http://192.168.1.9";
URL obj = null;
try{
obj = new URL(url);}
catch(IOException e){}
HttpURLConnection con = null;
try{
con = (HttpURLConnection) obj.openConnection();}
catch(IOException e){}
//con.setRequestProperty("User-Agent", USER_AGENT);
try{
con.setRequestMethod("GET");}
catch(ProtocolException e){}
try{
con.connect();}
catch(IOException e){}
try{
int responseCode = con.getResponseCode();}
catch(IOException e){}
BufferedReader in = null;
try{
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));}
catch(IOException e){}
String inputLine;
StringBuffer response = new StringBuffer();
try{
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}}
catch(IOException e){}
try{
in.close();}
catch(IOException e){}
//print result
System.out.println(response.toString());
return response.toString();
}
@Override
protected void onPostExecute(String result) {
String strParts[] = result.split("@");
ArrayList<dispencer> listAr = new ArrayList<dispencer>();
for(int i=0; i<strParts.length; i++){
listAr.add(new dispencer(strParts[i]));
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1);
for (int i = 0; i < listAr.size(); ++i) {
adapter.add(listAr.get(i).toString());
}
myList.setAdapter(adapter);
return ;
}
}
我讀我不得不使用getActivity方法,因爲我在我片段,而不是在上下文中。 編輯我coudn't擴展我的MainActivity類,因爲這個類已經擴展asyncTask。
顯示你的文件,你的類是否擴展了Fragment類?您的導入中包含片段類是否正確? –
你不在片段中,你在AsyncTask中,它不是上下文,也沒有getActivity()方法 – X3Btel