"Show once" Screen boolean Issue - java

I have an application that displays a splash screen then a 'Showonce' screen, I have used app prefs and a boolean "user_accept" to decide wether the screen gets displayed or not, trouble no matter if the boolean = true it still shows the page, please see my code for the pages, any help greatly appreciated :).
package com.overclockerz.webtest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Window;
import android.widget.Toast;
public class SplashScreen extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_layout);
final SharedPreferences settings = getSharedPreferences("APP_PREFS",
MODE_PRIVATE);
final boolean hasAgreed = settings.getBoolean("user_accepted", false);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (hasAgreed == false){
Intent intent = new Intent(SplashScreen.this, ShowOnce.class);
SplashScreen.this.startActivity(intent);
Toast.makeText(getApplicationContext(), "DEBUG: USER HAS NOT ACCEPTED",Toast.LENGTH_LONG).show();
}else if (hasAgreed == true){
Toast.makeText(getApplicationContext(), "DEBUG: USER HAS ACCEPTED",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
finish();
}
}, 2000); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
}
package com.overclockerz.webtest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
public class ShowOnce extends Activity implements OnClickListener {
Button show_options_dialog, accept_button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.show_once);
show_options_dialog = (Button) findViewById(R.id.show_options_dialog);
accept_button = (Button) findViewById(R.id.accept_button);
show_options_dialog.setOnClickListener(this);
accept_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == show_options_dialog){
Intent intent = new Intent(getApplicationContext(), SettingScreen.class);
startActivity(intent);
}
else if (v == accept_button){
SharedPreferences settings = getSharedPreferences("APP_PREFS",
MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean("user_accept", true);
Toast.makeText(getApplicationContext(), "DEBUG: USER CLICKED ACCEPT", Toast.LENGTH_LONG).show();
prefEditor.commit();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
}

you are saving user_accept and checking for user_accepted
Please use public static final String to avoid such problems:
public static final String USER_ACCEPTED = "accepted";
.........
prefEditor.putBoolean(USER_ACCEPTED , true);
.........
settings.getBoolean(USER_ACCEPTED , false);

Related

Adding new ListView item and get value of item from another activity

I am trying to make a "News App" with Android Studio. I have on my main activity a ListView and a floating button. On my second activity I got two TextViews, two EditViews and one Button. What I'd like to do is the following:
First I press on the floating Button from my main Activity. Then the second Activity should pop up and there I write on the two EditText's and then press on the button. After that I should go back to the main activity and there, a new Item should be added to the ListView. The new item should be filled with the text from the second activity's EditTexts.
This is my main activity:
package news;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get subject value from addpost Activity
final String new_value = getIntent().getStringExtra("newSubject");
String [] new_subject = new String []
{new_value};
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
final ListView post_view = findViewById(R.id.news_feed);
//Create Adapter to add the new subject to listview
if (new_subject != null) {
ArrayAdapter newslist_adapter = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
MainActivity.this.startActivity(intent);
}
});
}
}
This is the second activity(addpost_activity):
package news;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class addpost_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addpost_activity);
Button post_button = findViewById(R.id.post_btn);
final EditText subject_text = findViewById(R.id.subject_edit);
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
startActivity(intent);
}
}
});
}
}
My problem is now that the app crashes every time I start it. I also get this message from my logs:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Solved:
Thanks to Munir, the problem was solved.
Here are my activities
MainActivity:
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayAdapter newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
//Create Adapter to add the new subject to listview
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final ListView post_view = findViewById(R.id.news_feed);
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String new_value = data.getStringExtra("newSubject");
new_subject.add(new_value);
newslist_adapter = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
}
}
This is my second Activity(addpost_activity):
package news;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class addpost_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addpost_activity);
Button post_button = findViewById(R.id.post_btn);
final EditText subject_text = findViewById(R.id.subject_edit);
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
setResult(Activity.RESULT_OK, intent);
finish();
}
}
});
}
}
For that purpose I suggest using Fragments instead of two Activities. The MainActivity then holds all your data.
See Fragments guide.
From your MainActivity call the addpost_activity using startActivityForResult() method Instead of startActivity();
In your addpost_activity set the data which you want to return back to FirstActivity
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
setResult(Activity.RESULT_OK,intent );
finish();
}
}
});
And in the MainActivity Access the result by overriding onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("newSubject");
//Add this value to your adapter and call notifyDataSetChanged();
}
}
}
use ArrayList insted of String [] if you want to keep old entry in list change your code like below.
Main Activity
declare this variable as global
ArrayAdapter newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
set Adapter like
newslist_adapter = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
change startActivity to startActivityForResult
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent,100);
}
});
Override this method in onActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
String result=data.getStringExtra("newSubject");
new_subject.add(result)
//Add this value to your adapter and call newslist_adapter.notifyDataSetChanged();
}
}
And In your addpost_activity set the data which you want to return back
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
setResult(100,intent );
finish();
}
}
});
In MainActivity.java, you should override a function named "onActivityRecsult" this method will be called when you come back from second activity to first activity.

Having trouble in Session management

i m working on an application and i want to make user login only when he/she logouts his previous session but i m unable to do it. whenever i close my program and re-open it. it directs to Homepage again even if i had'nt logout. plz
package in.co.medimap.www.medimap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static in.co.medimap.www.medimap.R.layout.login;
/**
* Created by sony on 28-04-2016.
*/
public class login extends Activity {
TextView signup_text;
Button login_button;
EditText PHONE_NO,PASSWORD;
AlertDialog.Builder builder;
public static final String MyPREFERENCE ="Myprefs";
public static final String PHONE="phone";
public static final String PASS="password";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
signup_text=(TextView)findViewById(R.id.sign_up);
signup_text.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(login.this,register.class));
}
});
PHONE_NO=(EditText)findViewById(R.id.phone_no);
PASSWORD=(EditText)findViewById(R.id.password);
login_button=(Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ph = PHONE_NO.getText().toString();
String p=PASSWORD.getText().toString();
if (ph.equals("")||p.equals("")) {
builder = new AlertDialog.Builder(login.this);
builder.setTitle("Something went wrong...");
builder.setMessage("Please fill all the fields...");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
else
{
//see from here
sharedPreferences = getSharedPreferences(MyPREFERENCE,Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PHONE, ph);
editor.putString(PASS, p);
editor.commit();
BackgroundTask backgroundTask = new BackgroundTask(login.this);
backgroundTask.execute("login",ph,p);
}
}
});
}
}
this is my homeactivity where after logging user goes
and i want that if i hadn't logout then whenever i open my app it should start from here
package in.co.medimap.www.medimap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends Activity {
Button Logout = null;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Logout = (Button) findViewById(R.id.Logout);
textView = (TextView) findViewById(R.id.welcome_txt);
String message = getIntent().getStringExtra("message");
textView.setText(message);
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
If you want logout to happen each time user leaves the application, why don't you just do it manually?
you've already set Logout buttons setOnClickListener so just do this:
#Override
protected void onPause() {
super.onPause();
if(Logout != null) {
Logout.callOnClick();
}
}
This means every time user leaves this activity it will logout.
make sure you handle cases where if they leave activity but go to a different activity on your page, it doesn't log out.
=========== EDIT ===========
I'm guessing your login activity is the main activity that starts when application opens so just put this in onCreate before you perform any other tasks. right after setContentView, you should do this.
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
String phone = sharedPreferences.getString(PHONE, "");
String pass = sharedPreferences.getString(PASS, "");
if(!phone.isEmpty() && !pass.isEmpty()) {
// this means ID and passwords are already saved so just start your home activity here
startActivity(new Intent(context, MainActivity.class));
finish();
}
In your MainActivity:
Just read the values from SharedPreferences and login if you have to.
Hope this helps.
========== EDIT 2
Also, your Logout should look like this. Don't use commmit or clear. put empty values and use apply
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PHONE, "");
editor.putString(PASS, "");
editor.apply();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
}
});

java.lang.RuntimeException: Performing stop of activity that is not resumed:

I am getting a runtime exception when I am calling NavDrawerActivity from LoginScreen activity.
Error
java.lang.RuntimeException: Performing stop of activity that is not
resumed:
{com.example.owner.loginapp/com.example.owner.loginapp.NavDrawerActivity}
How to fix this error?
Here is my loginScreen code
package com.example.owner.loginapp;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.content.SharedPreferences;
public class LoginScreen extends AppCompatActivity {
ImageView image;
ImageView user_img;
ImageView pass_img;
Button log_in;
Button reg;
EditText editText_Username;
EditText editText_Pass;
UserSessionManager session;
private SharedPreferences sharedPreferences;
private static final String PREFER_NAME = "Reg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new UserSessionManager(getApplicationContext());
image = (ImageView) findViewById(R.id.imageView);
image.setImageResource(R.drawable.smile);
user_img = (ImageView) findViewById(R.id.user_img);
user_img.setImageResource(R.drawable.user_img);
pass_img = (ImageView) findViewById(R.id.pass_img);
pass_img.setImageResource(R.drawable.img_pass);
log_in = (Button) findViewById(R.id.btn_Login);
reg = (Button) findViewById(R.id.btn_Reg);
editText_Username = (EditText) findViewById(R.id.editText_UserName);
editText_Pass = (EditText) findViewById(R.id.editText_Password);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
image.setImageBitmap(icon);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = editText_Username.getText().toString();
String password = editText_Pass.getText().toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
String uName = null;
String uPassword = null;
if (sharedPreferences.contains("Name")) {
uName = sharedPreferences.getString("Name", "");
}
if (sharedPreferences.contains("Password")) {
uPassword = sharedPreferences.getString("Password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession(uName, uPassword);
Intent i = new Intent(getApplicationContext(), NavDrawerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.register);
Intent i = new Intent(getApplicationContext(), Reg.class);
startActivity(i);
}
});
}
}
I copied your code and tried to instantiate a Reg Activity class that I designed and everything worked fine. It is possible that you are doing something wrong in the 1onResumeoronCreate` of Reg class.
Post that class too for more information.

One Activity does not send Intent to another Activity

I got a problem: the first activity (below) doesn't send intent to second activity.
Here is MainActivity.java
package com.example.quizjavatest;
import android.os.Bundle;
import android.app.Activity;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
List<Question> quesList;
int score=0;
int qid=0;
ImageView quizimg;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DbHelper db=new DbHelper(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1); //question
rda=(RadioButton)findViewById(R.id.radio0); //option A
rdb=(RadioButton)findViewById(R.id.radio1); //option B
rdc=(RadioButton)findViewById(R.id.radio2); //option C
quizimg=(ImageView) findViewById(R.id.ImgQuiz); //img quiz
butNext=(Button)findViewById(R.id.button1); //button next
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<5){
currentQ=quesList.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
quizimg.setImageBitmap(currentQ.getBitmap());
qid++;
}
}
ResultActivity.java
package com.example.quizjavatest;
import android.os.Bundle;
import android.app.Activity;
import android.widget.RatingBar;
import android.widget.TextView;
public class ResultActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_results);
RatingBar bar=(RatingBar)findViewById(R.id.ratingBar1);
bar.setNumStars(5);
bar.setStepSize(0.5f);
//get text view
TextView t=(TextView)findViewById(R.id.textResult);
//get score
Bundle b = getIntent().getExtras();
int score= b.getInt("score");
//display score
bar.setRating(score);
switch (score)
{
case 1:
case 2: t.setText("Oopsie! Better Luck Next Time!");
break;
case 3:
case 4:t.setText("Hmmmm.. Someone's been reading a lot of trivia");
break;
case 5:t.setText("Who are you? A trivia wizard???");
break;
}
}
}
Change your intent:
Intent intent = new Intent(this, ResultActivity.class); //better use `this` instead of global context
intent.putExtras("score", score); //Put your score to your next
startActivity(intent);
finish();
No need to use Bundle unless you're passing Object, Intent's extras they are Bundle already, don't do same twice.
In ResultActivity catch it:
Intent intent = getIntent();
int score = intent.getIntExtra("score");
Hope this will solve your problem.

Switching activities/passing data between activities

So using suggestions from the last question I asked, I figured out how to call BarCodeScanner, and return the value to a field. so now, I have a toast that says "successful scan" and then I want to pass the result to a new activity. when I comment out my intent, everything works (minus the passing of data/switching of screen, obviously) but when I run my project as is, it FC's... no errors reported by eclipse in code or XML. Any insights?
package com.mhe.test.scan;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myScanButton = (Button) findViewById(R.id.myScanButton);
totalbox = (EditText) findViewById(R.id.tBox);
myScanButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
});
}
private EditText totalbox;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
final String contents = intent.getStringExtra("SCAN_RESULT");
if ( totalbox != null )
totalbox.setText(contents);
Context context = getApplicationContext();
CharSequence text = "Successful Scan";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent i = new Intent(main.this, Result.class);
i.putExtra("SNARP", "SCAN_RESULT");
startActivityForResult(i, 0);
} else if (resultCode == RESULT_CANCELED) {
if ( totalbox != null )
totalbox.setText("bummer");
}
}
}
}
And then to handle the data being passed, in the new activity:
package com.mhe.test.scan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Result extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent i = getIntent();
Bundle b = i.getExtras();
String foosh = b.getString("SNARP");
EditText box1 = (EditText) findViewById(R.id.tBox1);
box1.setText(foosh);
Try sending a Bundle object when calling the new intent.
Intent i = new Intent(main.this, Result.class);
Bundle b = new Bundle();
b.putString("SNARP", "SCAN_RESULT")
i.putExtras(b);
Try getting string in the child Activity this way.
public class Result extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent i = getIntent();
String foosh = i.getStringExtra("SNARP");

Categories

Resources