I've got two classes. I want to invoke the "saveq" method in the QuestionPicker.class. This method saves some Strings into the SharedPreferences. I want to invoke that method from another class, that is called Questions. I want to invoke the method using reflection, but my code doesn't work.. I think the problem is somewhere at the reflection, but I can't see it. Can someone see the problem? Thanks
Here is the QuestionPicker.class
public class QuestionPicker {
public void saveq() {
// MyApplication Class calls Context
Context context = MyApplication.getAppContext();
// Values to save
String Q1 = "SomeQuestion";
String Q2 = "SomeOtherQuestion";
String Q3 = "AndEvenMoreQuestions";
// Save the Strings to SharedPreferences
SharedPreferences.Editor editor = context.getSharedPreferences("QuestionsSaver", 0).edit();
editor.putString("Q1", Q1);
editor.putString("Q2", Q2);
editor.putString("Q3", Q3);
editor.apply();
}
}
And here is the Questions.class
public class Questions extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
// storing string resources into Array
String[] subjects = getResources().getStringArray(R.array.subjects);
ListView lv = (ListView) findViewById(R.id.listView);
// Binding resources Array to ListAdapter
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, subjects);
lv.setAdapter(adapter);
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Invoke the saving Method
try {
Class cls = Class.forName("com.test.QuestionsPicker");
Object obj = cls.newInstance();
Method method = cls.getMethod("saveq");
method.invoke(obj);
} catch(Exception ex){
ex.printStackTrace();
}
}
});
}
}
Aucun commentaire:
Enregistrer un commentaire