我想填写并显示素数的listview
。PrimeNumbers类的arraylist
似乎已被填充但是当我想将它分配给列表视图时它会赢得#t工作
问题是当从处理程序调用PrimeNumbersActivity时,listview未填充且新活动中没有显示任何内容。 真的很感激一些帮助。
PrimeNumbers Class
public class PrimeNumbers {
public ArrayList<Integer> primeNumbers = new ArrayList<>();
public PrimeNumbers(ArrayList<Integer> primeNumbers){
this.primeNumbers = primeNumbers;
}
public PrimeNumbers() {
}
}
处理程序类
public class MyHandler extends Handler {
ProgressDialog progressDialog;
Context context;
public MyHandler(ProgressDialog progressDialog, Context context) {
this.progressDialog = progressDialog;
this.context = context;
}
@Override
public void handleMessage(Message msg) {
findPrimeNumber(Integer.parseInt(msg.obj.toString()));
}
public void findPrimeNumber(int number){
ArrayList<Integer> primeNumbers = new ArrayList<>();
boolean isPrimeNumber;
PrimeNumbers primeNumbers1 = new PrimeNumbers(primeNumbers);
for(int i = 2; i <= number; i++){
isPrimeNumber = true;
for(int j = 1; j <= i; j++){
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(j != 1 && j != i){
if(i%j == 0){
isPrimeNumber = false;
break;
}
}
}
if(isPrimeNumber){
primeNumbers.add(i);
}
progressDialog.setProgress(i*100/number);
if(progressDialog.getProgress() == progressDialog.getMax()){
progressDialog.dismiss();
Intent intent = new Intent(context.getApplicationContext(),PrimeNumbersActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
for (int i :
primeNumbers1.primeNumbers) {
Log.d(TAG, i + "");
}
}
}
PrimeNumbersActivity类
public class PrimeNumbersActivity extends AppCompatActivity {
private PrimeNumbers primeNumbers = new PrimeNumbers();
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime_numbers);
listView = (ListView) findViewById(R.id.list1);
ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_2, primeNumbers.primeNumbers);
listView.setAdapter(arrayAdapter);
}
}
答案 0 :(得分:1)
你可以尝试任何人,
1.使用 putExtra()
,
intent.putExtra("ARRAYLIST",(Serializable) primeNumbers);
在您的活动中,更改此行
ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_2, (ArrayList<Integer>) getIntent().getSerializableExtra("ARRAYLIST"));
2.使用 singleton class
public class PrimeNumbers {
private static PrimeNumbers primenumbersOBJ=new PrimeNumbers();
public ArrayList<Integer> primeNumbersArray = new ArrayList<>();
public static PrimeNumbers getInstance(){
return primenumbersOBJ;
}
private PrimeNumbers() {
}
在Handler类中,在开始意图之前
PrimeNumbers.getInstance().primeNumbersArray=resultarray;
在您的活动中,使用
PrimeNumbers.getInstance().primeNumbersArray