我对android编程很陌生,我已经构建了一个片段,我试图将主要活动上下文放在ListViewAdapter中但是我得到一个错误说:android.app.activity不能无法应用于android.content.context 我不一定确定为什么会在ListViewAdapter中发生这种情况,而在InputStream下面,似乎不会出现问题。
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import Model.Statistics;
import util.DatabaseHelper;
import static com.example.sheyda.scorestats.Constants.FIFTH_COLUMN;
import static com.example.sheyda.scorestats.Constants.FIRST_COLUMN;
import static com.example.sheyda.scorestats.Constants.FOURTH_COLUMN;
import static com.example.sheyda.scorestats.Constants.SECOND_COLUMN;
import static com.example.sheyda.scorestats.Constants.SIXTH_COLUMN;
import static com.example.sheyda.scorestats.Constants.THIRD_COLUMN;
public class TopFragment extends Fragment {
private InputStreamReader fileReader;
private BufferedReader buffReader;
private ArrayList<HashMap<String, String>> list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_f1, container, false);
ListView listview = (ListView) v.findViewById(R.id.listView_SID);
try {
populateLV("stats.txt");
} catch (IOException e) {
e.printStackTrace();
}
ListViewAdapter adapter = new ListViewAdapter(getActivity().getBaseContext(), list);
listview.setAdapter(adapter);
return v;
}
public void populateLV(String fileName) throws IOException {
list = new ArrayList<HashMap<String, String>>();
Statistics stat = new Statistics();
InputStream descriptor = getActivity().getBaseContext().getAssets().open(fileName);
fileReader = new InputStreamReader(descriptor);
buffReader = new BufferedReader(fileReader);
String line;
// Counter stops at 40 because maximum number of students allowed is 40
int count = 0;
while ((line = buffReader.readLine()) != null && count <= 40) {
String[] l = line.split("~");
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, l[0]);
temp.put(SECOND_COLUMN, l[1]);
temp.put(THIRD_COLUMN, l[2]);
temp.put(FOURTH_COLUMN, l[3]);
temp.put(FIFTH_COLUMN, l[4]);
temp.put(SIXTH_COLUMN, l[5]);
list.add(temp);
count++;
}
}
}
答案 0 :(得分:1)
到处使用getActivity()
代替getActivity().getBaseContext()
。