我正在制作一个android移动应用。我试图在MainActivity中保存数据。但是有太多数据,我发现将其保留在MainActivity中是不合适的。因此,我决定创建一个名为Data的Java类来保留代码。但是以某种方式,我无法调用Data类。
Data.java
package com.example.lenovo.pointofinterest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Data extends AppCompatActivity {
//a list to store all the places
List<Places> placesList;
//the recyclerview
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the placesList
placesList= new ArrayList<>();
//adding some items to our list
placesList.add(
new Places(
1,
"Adventure Zone Theme Park",
"13.3 inch, Silver, 1.35 kg",
"Amusement Park",
"10.00am - 7.00pm (Daily)",
R.drawable.adventure_zone_theme_park));
placesList.add(
new Places(
1,
"Escape Penang Theme Park",
"14 inch, Gray, 1.659 kg",
"Amusement Park",
"10.00am - 6.00pm (Tue - Sun)",
R.drawable.escape_penang_theme_park));
placesList.add(
new Places(
1,
"Countryside Stables Penang",
"13.3 inch, Silver, 1.35 kg",
"Animal Lover",
"2.00pm - 7.00pm (Daily)",
R.drawable.countryside_stables_penang));
//creating recyclerview adapter
PlacesAdapter adapter = new PlacesAdapter (this, placesList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MainActivity.java
package com.example.lenovo.pointofinterest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity{
}
我尝试通过遵循此处的提示(可能是onCreate引起的提示)来编辑代码,但是我仍然无法修复它。请帮忙。谢谢。
答案 0 :(得分:1)
我觉得你打算这样做
public class Data {
//a list to store all the places
public static List<Places> placesList = Arrays.asList(new Places(), new Places());
}
就是这样。然后在MainActivity(仍然需要扩展一些Activity类)中,您可以引用Data.placesList
放入适配器
PlacesAdapter adapter = new PlacesAdapter(MainActivity.this, Data.placesList);
如果需要,可以将适配器放入数据类,但是应该使用RecyclerView并从MainActivity中找到它。
答案 1 :(得分:0)
首先,您的MainActivity需要扩展AppComapActivity
第二,您需要在MainActivity中进行创建。
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent(getApplicationContext(), YourClass.class);
startActivity(intent);
}
然后,您可以在主活动中调用您的课程。