Trying to retrieve data from a Shared Preferences - android

I have tried to retrieve data from Shared Preferences and tried to intent it over to my main activity where I want it to display the score the user got. There are no errors, it just doesn't save the best_score_number_tv or doesn't correctly send it over. I hope there isn't too much wrong :(
Main_Screen
public class Main_Screen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
getSupportActionBar().hide();
//SETS CUSTOM FONT
TextView main_screen_titleone = (TextView)findViewById(R.id.main_screen_titleone);
TextView main_screen_titletwo = (TextView)findViewById(R.id.main_screen_titletwo);
TextView best_score_tv = (TextView)findViewById(R.id.best_score_tv);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
main_screen_titleone.setTypeface(myCustomFont);
main_screen_titletwo.setTypeface(myCustomFont);
best_score_tv.setTypeface(myCustomFont);
best_score_number_tv.setTypeface(myCustomFont);
//******************;
retrieveBestScore();
}
public void startTheGame(View view){
Intent intent = new Intent(this, press_screen.class);
startActivity(intent);
}
public void retrieveBestScore(){
Intent getBestScore = getIntent();
int BEST_SCORE = getBestScore.getIntExtra("BEST_SCORE", 0);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
best_score_number_tv.setText(BEST_SCORE + "");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main__screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
press_screen
public class press_screen extends ActionBarActivity {
private int time_left;
private int amountOfTapsNumber;
private int bestScore;
TextView amountOfTaps;
TextView timeLeftNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_screen);
getSupportActionBar().hide();
timer.start();
loadInfo();
}
//Create Timer
CountDownTimer timer = new CountDownTimer(21000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftNumber = (TextView) findViewById(R.id.time_left_number_tv);
time_left = Integer.valueOf(timeLeftNumber.getText().toString()) - 1;
timeLeftNumber.setText(time_left + "");
}
#Override
public void onFinish() {
bestScore = amountOfTapsNumber;
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Intent sendBestScore = new Intent(press_screen.this, Main_Screen.class);
sendBestScore.putExtra("BEST_SCORE", bestScore);
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
startActivity(goBackToMainActivity);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_press_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void triggerTapOnMainButton(View view) {
amountOfTaps = (TextView) findViewById(R.id.amount_of_taps);
amountOfTapsNumber = Integer.valueOf(amountOfTaps.getText().toString()) + 1;
amountOfTaps.setText(amountOfTapsNumber + "");
}
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt("BEST_SCORE", bestScore);
edit.commit();
}
public void loadInfo(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
int BEST_SCORE = sp.getInt("BEST_SCORE", 0);
}
}

If you want to use and Intent you should put the extra in the intent you pass to
startActivity
so
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
goBackToMainActivity.putExtra("BEST_SCORE", bestScore);
startActivity(goBackToMainActivity);
Alternatively you could just save the score from your press_screen activity
after
bestScore = amountOfTapsNumber;
saveInfo("BEST_SCORE", bestScore);
Also, if you are going to pass in a key to save the info, you might consider using it
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt(key, bestScore);
edit.commit();
}
And when retrieving
public int retrieveInt(String key){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getInt(key, 0);
}

Related

Passing variable from onCreate() to onPause()

I have a variable storyID that I have successfully set in onCreate. But when I try to access it in onPause it returns 0.
I presume this is a scoping issue, but can't see where I'm going wrong?
public class StoryBodyActivity extends AppCompatActivity {
private TextView storyBodyTextView;
private ScrollView storyBodyScrollView;
public int storyID;
Parcelable state;
int scrollY;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_story_body, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_body);
Bundle extras = getIntent().getExtras();
String story = extras.getString("story");
int storyID = extras.getInt("story_id");
Log.i("stories", Integer.toString(storyID));
// show back arrow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(story);
storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);
DatabaseHelper db = new DatabaseHelper(this);
String storyBody = db.getStoryBody(storyID);
storyBodyTextView.setText(Html.fromHtml(storyBody));
if(state != null) {
Log.d("pause", "trying to restore textview state..");
storyBodyTextView.onRestoreInstanceState(state);
}
int scroll = storyBodyScrollView.getScrollY();
Log.i("scroll", Integer.toString(scroll));
}
#Override
public void onPause() {
// Log.d("pause", "saving listview state # onPause");
// state = storyBodyTextView.onSaveInstanceState();
scrollY = storyBodyScrollView.getScrollY();
// Log.i("scroll", Integer.toString(scrollY));
Log.i("insert", Integer.toString(storyID));
DatabaseHelper db = new DatabaseHelper(this);
db.saveScrollPosition(scrollY, storyID);
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Remove int from int storyID in the onCreate method

Persist values across the lifetime of an app - Pause / resume countdown timer

I want to create a countdown such that when the app is completely closed, the countdown timer is paused and saved. When the app is opened again, the countdown resumes where it left off.
My idea was to save the value "millisUntilFinished" in the "onStop" when the app is closed and in the "onResume" continue the countdown when the app is opened.
The problem is that I don't know how to do it, someone help me?
The code of my countdown:
public class MainActivity extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.b1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
// this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void a(View view){
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv1.setText("La cuenta llega a 0 en: " + millisUntilFinished / 1000);
}
public void onFinish() {
tv1.setText("Listo!");
}
}.start();
}
Use SharedPreferences.
onResume(){
SharedPreferences prefs =
getSharedPreferences("PREF_NAME", MODE_PRIVATE);
int startTime = prefs.getInt("PAUSED_TIME", 0); //0 is the default value.
}
onPause(){
SharedPreferences.Editor editor =
getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putInt("PAUSED_TIME", time);
editor.commit();
}

Updating a listview with custom base adapter when coming back into the activity?

I am trying to update my listview when saving a new survey in my app.
But i'm not able to achieve that function yet.
Here's a bit of my code :
public class MainActivity extends AppCompatActivity {
private ListView lv1;
private GeoXML xml;
private ArrayList<Releve> listeReleve = new ArrayList<Releve>();
public void onClickUndefined(View view) {
Toast.makeText(view.getContext(), "Fonction non implémenté", Toast.LENGTH_LONG).show();
}
public void onClickCreateReport(View view) {
Intent intent = new Intent(MainActivity.this, NewSurveyActivity.class);
intent.putExtra("ReleveExistant", false);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
listeReleve.clear();
scanForReleve();
lv1.deferNotifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageView imgNouveauReleve = (ImageView) findViewById(R.id.Img_Nouveau_Releve);
ImageView imgBoutonAjouter = (ImageView) findViewById(R.id.bouton_ajouter);
TextView txtNouveauReleve = (TextView) findViewById(R.id.MA_TitreListeReleve);
lv1 = (ListView) findViewById(R.id.MA_ListeReleves);
//supprimerTout();
//scanForReleve();
//ArrayList<Releve> listeReleve = GetSearchResults();
//listeReleve.clear();
if (!listeReleve.isEmpty()) {
imgNouveauReleve.setVisibility(View.INVISIBLE);
imgBoutonAjouter.setVisibility(View.VISIBLE);
txtNouveauReleve.setVisibility(View.VISIBLE);
lv1.setVisibility(View.VISIBLE);
lv1.setAdapter(new MyCustomBaseAdapter(this, listeReleve));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
Releve fullObject = (Releve) o;
//Toast.makeText(MainActivity.this, "Vous avez choisi : " + " " + fullObject.getProjet(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, NewSurveyActivity.class);
intent.putExtra("Releve", fullObject);
intent.putExtra("ReleveExistant", true);
startActivity(intent);
}
});
} else {
imgNouveauReleve.setVisibility(View.VISIBLE);
imgBoutonAjouter.setVisibility(View.INVISIBLE);
txtNouveauReleve.setVisibility(View.INVISIBLE);
lv1.setVisibility(View.INVISIBLE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean supprimerTout (){
String filepath = "";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File dir = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
//File dir = new File(releve.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
dir.delete();
return true;
}
public void scanForReleve(){
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir("", Context.MODE_PRIVATE);
File dir = new File(directory.getPath() + "/releve/");
GeoXML xmlObj = new GeoXML();
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
listeReleve.add(xmlObj.lireXML(directory.getPath(), children[i]));
}
}
}
}
It's the first time i'm playing around with the onResume() method.
Don't know if it's the proper way to proceed.
You need to get notified of the result of the NewSurveyActivity using startActivityForResult(). Use the following link to implement it.
How to manage `startActivityForResult` on Android?
You can update the list in the case of RESULT_OK only.

One Result Activity with many Activities

I have many activities which have 1 resultant activity. Does anyone know how to separate it, the result will display one result from many activity. If i run it it will display result fruitQuestion and AnimalQuestion.
Test.java:
public class Test extends Activity {
Button btnFruitQ,btnAnimalQ;
ToggleButton tb;
public static boolean tbflag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btnFruitQ = (Button) findViewById(R.id.btnFruitQ);
btnAnimalQ = (Button) findViewById(R.id.btnAnimalQ);
tb = (ToggleButton) findViewById(R.id.ToggleButton);
btnFruitQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tbflag=tb.isChecked();
startActivity(new Intent(Test.this, FruitQuestion.class));
}
});
btnAnimalQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tbflag=tb.isChecked();
startActivity(new Intent(Test.this, AnimalQuestion.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FruitQuestion.java:
public class FruitQuestion extends Activity {
TextView tv;
Button btnNext;
RadioGroup rg;
RadioButton bt1,bt2,bt3;
String Question[]={"HAHA","HAHA2","HAHA3"};
String ans[]={"i1","12","i3"};
String opt[]={"i1","lali","uu","12","hehe","oo","i3","jj","cc"};
int flag=0;
public static int mark,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fruit_question);
tv=(TextView) findViewById(R.id.tvque);
btnNext=(Button) findViewById(R.id.btnNext);
rg = (RadioGroup) findViewById(R.id.rg);
bt1 = (RadioButton) findViewById(R.id.btn1);
bt2 = (RadioButton) findViewById(R.id.btn2);
bt3 = (RadioButton) findViewById(R.id.btn3);
tv.setText(Question[flag]);
bt1.setText(opt[0]);
bt2.setText(opt[1]);
bt3.setText(opt[2]);
Toast.makeText(this,"Negative Mark : "+Test.tbflag,1000).show();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton uans=(RadioButton)findViewById(rg.getCheckedRadioButtonId());
String ansText= uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag]))
{
correct++;
}
else
{
wrong++;
}
flag++;
if(flag<Question.length)
{
tv.setText(Question[flag]);
bt1.setText(opt[flag*3]);
bt2.setText(opt[(flag*3)+1]);
bt3.setText(opt[(flag*3)+2]);
}
else
{
if(Test.tbflag)
{
mark=correct-wrong;
}
else
{
mark=correct;
}
Intent in=new Intent(getApplicationContext(),ResultActivity.class);
startActivity(in);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_fruit_question, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ResultActivity.java:
public class ResultActivity extends Activity {
TextView tv;
Button btnRestart;
StringBuffer sb=new StringBuffer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
tv=(TextView)findViewById(R.id.tvres);
btnRestart=(Button)findViewById(R.id.btnRestart);
sb.append("Correct Answer : " + FruitQuestion.correct);
sb.append("\nWrong Answer : " + FruitQuestion.wrong);
sb.append("\nFinal Score : " + FruitQuestion.mark);
tv.setText(sb);
FruitQuestion.correct = 0;
FruitQuestion.wrong = 0;
sb.append("Correct Answer : "+AnimalQuestion.correct);
sb.append("\nWrong Answer : "+AnimalQuestion.wrong);
sb.append("\nFinal Score : " + AnimalQuestion.mark);
tv.setText(sb);
AnimalQuestion.correct=0;
AnimalQuestion.wrong=0;
btnRestart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in=new Intent(getApplicationContext(),Test.class);
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_result, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use Intent Extras to tell ResultActivity which Activity called it, and display the corresponding results.
Note that you should also re-factor your code so that you're not using static variables in the Activities to store data, you could use SharedPreferences instead.
Just to get you started though, here is what you could do in the short term:
In FruitQuestion, you would have:
Intent in=new Intent(getApplicationContext(),ResultActivity.class);
in.putExtra("question", "fruit");
startActivity(in);
And in AnimalQuestion, you would have:
Intent in=new Intent(getApplicationContext(),ResultActivity.class);
in.putExtra("question", "animal");
startActivity(in);
Then, in ResultActivity, capture the Intent Extra, and show corresponding result:
Bundle extras = this.getIntent().getExtras();
if (extras != null){
String question = extras.getString("question");
if (question.equals("fruit")) {
sb.append("Correct Answer : " + FruitQuestion.correct);
sb.append("\nWrong Answer : " + FruitQuestion.wrong);
sb.append("\nFinal Score : " + FruitQuestion.mark);
tv.setText(sb);
FruitQuestion.correct = 0;
FruitQuestion.wrong = 0;
}
else if (question.equals("animal")) {
sb.append("Correct Answer : " + AnimalQuestion.correct);
sb.append("\nWrong Answer : " + AnimalQuestion.wrong);
sb.append("\nFinal Score : " + AnimalQuestion.mark);
tv.setText(sb);
AnimalQuestion.correct = 0;
AnimalQuestion.wrong = 0;
}
}
Firstly, give your Intent instance a different name. Other than in. You can put extra in intent object and send it to ResultActivity
Like this
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("activityName", "FruitQuestion");
startActivity(intent);
In ResultActivity
Intent intent = getIntent();
String activityName = intent.getStringExtra("activityName");
Check your activityName value and show its results.
I think I understand you, you want to pass some values from A-activity to B-activity.
To pass data between activities, you can use the same intent you are sending.
Here an example:
Intent i = new Intent(this, ActivityA.class);
i.putExtra("key1", value1);
i.putExtra("key2", value2);
startActivity(i);
putExtra method allow pass multiples kinds of value, like boolean, string, integer...
Then, in the another activity, in onCreate method, you can get this value this way:
String save = getIntent().getExtras().getString("key1");
Or
Bundle bundle = getIntent().getExtras();
boolean check = bundle.getBoolean("key2");
I hope it help you :)

error whilst passing values between activities

I have an activity which has an edit text which becomes visible when a button is clicked. I fill the edit text up and click another button. On clicking this button the edit text content must be sent to another activity.The first activity takes the edit text and queries a list of data from my Parse database and shows it in a ListView in the Second Activity.But whenever i click the first button(after entering the string) the app crashes.This is the first activity
public class MainActivity extends ActionBarActivity {
String name;
EditText search;
Button g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpSpinners();
Parse.initialize(this, "AAh5US7zhbYyFBexsv07cjo34ZZiB7KNe9SuTv7e",
"eKUG1pYaV50hVyDC9d4qZc4qf1dCtOTqnX92eGJV");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation();
search = (EditText) findViewById(R.id.search);
g = (Button) findViewById(R.id.Go);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void byName(View v) {
search.setVisibility(View.VISIBLE);
search.requestFocus();
g.setVisibility(View.VISIBLE);
}
public void Go(View v) {
name = search.getText().toString();
final Intent i;
i = new Intent(MainActivity.this, ResterauntList1.class);
i.putExtra("restrauntName", name);
startActivity(i);
}
}
In the above byName is the onClick for making the EditText visible, and Go is the onClick for getting my EditText string and passing it to the next activity. The second activity is below
public class ResterauntList1 extends Activity {
String rValue;
ArrayAdapter<String> adapter;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resteraunt_list1);
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
setContentView(R.layout.activity_resteraunt_list);
populateList(rValue, "name");
}
private void populateList(final String Value, final String Key) {
ParseQueryAdapter.QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
#Override
#SuppressWarnings({ "unchecked", "rawtypes" })
public ParseQuery create() {
ParseQuery query = new ParseQuery("resdb");
query.whereEqualTo(Key, Value);
return query;
}
};
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(
this, factory);
adapter.setTextKey("name");
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
#Override
public void onLoading() {
mProgressDialog = new ProgressDialog(ResterauntList1.this);
mProgressDialog.setTitle("Searching for " + Value);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
public void onLoaded(List<ParseObject> objects, Exception e) {
mProgressDialog.dismiss();
}
});
final ListView listView = (ListView) findViewById(R.id.restListView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ParseObject object = (ParseObject) listView
.getItemAtPosition(position);
String Id = object.getObjectId();
Intent i = new Intent(getApplicationContext(),
SingleRestraunt.class);
i.putExtra("restId", Id);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.resteraunt_list1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The error as stated above occurs when I click the Go button.The error is
09-02 14:58:46.443: E/AndroidRuntime(3061): Process: com.example.gastronomaapp, PID: 3061
09-02 14:58:46.443: E/AndroidRuntime(3061): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gastronomaapp/com.example.gastronomaapp.ResterauntList1}: java.lang.NullPointerException
Any idea where I am making a mistake? The funniest thing almost the same code has worked in another part of my app. absolutely clueless whats wrong.
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
change to
rValue = getIntent().getStringExtra("restrauntName");
You put the string directly on the intent, not packaged in a bundle.

Categories

Resources