I am currently working on a quiz application whereby i need to review answered questions after each quiz session. So, am passing the number of questions attempted as an int value with a bundle to the next activity.
So, am looping forward and backwards against my array of questions in which the index limit is the int which was passed from previous activity. However, am having some trouble as it isn't looping correctly. How do i get round this?
Question Class
class Question{
// array of questions
private String mQuestions [] = {
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// method returns number of questions
int getLength(){
return mQuestions.length;
}
// method returns question from array textQuestions[] based on array index
String getQuestion(int a) {
return mQuestions[a];
}
}
MainActivity.java
Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
intent.putExtra("quizNumber", mquizNumber);
startActivity(intent);
ResultsActivity.java
Intent intent = new Intent(ResultsActivity.this, ReviewActivity.class);
Bundle exBundle= getIntent().getExtras();
int intValue= 0;
if (exBundle != null) {
intValue = exBundle.getInt("quizNumber");
}
intent.putExtra("quizNumber", intValue);
startActivity(intent);
ReviewActivity.java
public class ReviewActivity extends AppCompatActivity {
private Question mQuestionLibrary = new Question();
private TextView mQuestionText;
private int intValue; // int value from quiz activity to be passed here
private int mQuestionNumber = 1; // current question number
//navigation buttons for looping through array
private Button mPrevious;
private Button mNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
setContentView(R.layout.activity_beginner_review);
mQuestionText = (TextView) findViewById(R.id.txtQuestion);
//setting buttons
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
// retrieve the number of attempted questions int value from quizActivity in Bundle
Bundle exBundle= getIntent().getExtras();
intValue = 0;
if (exBundle != null) {
intValue = exBundle.getInt("quizNumber");
}
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(true);
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(false);
}
});
}
// logic for looping through array.
private void updateQuestion(boolean forward) {
animateAnswerButton();
if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
mQuestionNumber++;
else if (mQuestionNumber>0)
mQuestionNumber--;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
Try this code.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
if(extras.containsKey("quizNumber")) {
intValue=getIntent().getExtras().getInt("quizNumber")
}
}
updateQuestion(true,intValue);
or
updateQuestion(false,intValue);
private void updateQuestion(boolean forward, int intValue) {
animateAnswerButton();
// also print toast of int value for checking value
if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
mQuestionNumber++;
else if (mQuestionNumber>0)
mQuestionNumber--;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
Also toast or log your mquizNumber in MainActivity whether you're putting correct value in bundle or not.
Use this
In your sender class
//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putInt("DATA", value);
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
in your reciver class
Bundle bundle = getIntent().getExtras();
//Extract the data…
String venName = bundle.getInt("DATA");
I think you should do this.
class DataStore{/*New class DataStore*/
public static int quizNumber=0;
}
/Mainactivity/
DataStore.quizNumber=mquizNumber;
startActivity(MainActivity.this, ResultsActivity.class);
/ReviewActivity/
intValue=DataStore.quizNumber;
Related
I am developing an android app and just need some help on selecting the correct text files and keeping a count of the number of clicks for buttons.
So basically I have two activity classes. The homepage of the app is stored in the MainActivity class and the other class is known as Content
In the MainActivity class there are three buttons:
Jokes,
Poems
and Funny Stories
Basically whichever option the user selects out of those three buttons, the content on the next page (Content class) will display the correct passage of text relating to the choice selected.
Currently my code works for jokes when the user selects jokes and the content it displays is randomly selected from the jokes.txt file.
MainActivity
public class MainActivity extends AppCompatActivity{
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage();
}
});
}
private void openContentPage(){
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
startActivity(intentContentPage);
}
}
Content
public class Content extends AppCompatActivity{
Button backButton;
Button selectAnotherButton;
TextView contentText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
contentText = findViewById(R.id.content_text);
contentText.setMovementMethod(new ScrollingMovementMethod());
setContent();
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContent();
}
});
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
backToMainActivity();
}
});
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
private void setContent(){
String text = "";
String randomJoke = "";
try {
// file to inputstream
InputStream input = getAssets().open("files/jokes.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
text = new String(buffer);
String[] jokes = text.split("###");
Random rand = new Random();
int randomIndex = rand.nextInt(jokes.length);
randomJoke = jokes[randomIndex];
}
catch (Exception e) {
System.out.println(e);
}
contentText.setText(randomJoke);
}
}
However this code needs to be manipulated so that it includes Poems and Funny Stories. Basically if the user selects Poems then it will grab the content from the poems.txt file, if they select Funny Stories then it will grab from the funnystories.txt file. Also if they select the Select Another button, it will randomly select a new entry from the correct text file. Like I said the code I have done works for jokes only, but I need to make it more dynamic so it would work for poems and funny stories too depending on which option the user selected from the homepage.
One final thing as well. I want a count of the number of times the user has clicked on either Jokes, Poems, Funny Stories from MainActivity and also add Select Another button to the count as well.
How can this be implemented?
UPDATE:
Trying to receive the intent I receive the following error from this code:
private void setContent(){
String text = "";
String randomText = "";
String keyPageValue = getIntent().getStringExtra("keyPage");
String fileName = "";
if(keyPageValue.equals("0")){
fileName.equals("files/jokes.txt");
}
else if (keyPageValue.equals("1")){
fileName.equals("files/poems.txt");
}
else if (keyPageValue.equals("2")){
fileName.equals("files/funnystories.txt");
}
try {
InputStream input = getAssets().open(fileName);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
text = new String(buffer);
String[] splitText = text.split("###");
Random rand = new Random();
int randomIndex = rand.nextInt(splitText.length);
randomText = splitText[randomIndex];
}
catch (Exception e) {
System.out.println(e);
}
contentText.setText(randomText);
}
Stack Trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mima.chilltime, PID: 18747
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mima.chilltime/com.mima.chilltime.Content}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3150)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
...
In order to do that you can pass an int value which denotes the type of button clicked by the user:-
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage(0);
}
});
poemsButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage(1);
}
});
funnyStoriesButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage(2);
}
});
private void openContentPage(int v) {
if(v == 0) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intent.putExtra("keyPage",0);
startActivity(intentContentPage);
}
else if(v == 1) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intent.putExtra("keyPage",1);
startActivity(intentContentPage);
}
else {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intent.putExtra("keyPage",2);
startActivity(intentContentPage);
}
}
And in the next activity you can receive intent. Fetch the value and check based on that open the content page.
I am new to app development and so far my app is working as intended but only when I launch it on my device from Android Studio. For example, I have once instance variable that I give a value of 1 in the onCreate() method. When I launch the app from android studio on to my device, it works fine and the variable has a value of 1. However, when I launch it from my device without using android studio, the variable is given a value of 0. I have also found that I will get a bunch of NullPointerExceptions on variables that I know should have a value, and once again it works when launched from Android Studio, but not when launched from the device.
Here is MainActivity
public class MainActivity extends AppCompatActivity
{
private ArrayList<String> arrayList;
private ArrayList<ListItem> itemList;
private ArrayAdapter<String> adapter;
private EditText txtInput;
private int payRoll;
private String value;
private Intent mainToPayroll;
private int hours;
private int earnings;
private ArrayList<Integer> rollList;
private ArrayList<Integer> hourList;
private ArrayList<Integer> wageList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollList = new ArrayList<>(0);
hourList = new ArrayList<>(0);
wageList = new ArrayList<>(0);
payRoll = 1;
Bundle bun = getIntent().getExtras();
if(bun != null)
{
rollList = bun.getIntegerArrayList("rolls");
hourList = bun.getIntegerArrayList("hours");
wageList = bun.getIntegerArrayList("wages");
payRoll = bun.getInt("roll");
}
ListView listView = (ListView) findViewById(R.id.listv);
String[] items = {};
arrayList = new ArrayList<>(Arrays.asList(items));
itemList = new ArrayList<>(0);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtitem, arrayList);
listView.setAdapter(adapter);
Button btAdd = (Button) findViewById(R.id.btadd);
mainToPayroll = new Intent(this, PayrollActivity.class);
if(rollList != null)
{
for (int i = 0; i < rollList.size(); i++) {
ListItem newItem = new ListItem(rollList.get(i), hourList.get(i), wageList.get(i));
arrayList.add(newItem.toString());
itemList.add(newItem);
adapter.notifyDataSetChanged();
}
rollList.clear();
hourList.clear();
wageList.clear();
}
btAdd.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
ListItem newItem = new ListItem(payRoll, 0, 0);
arrayList.add(newItem.toString());
itemList.add(newItem);
adapter.notifyDataSetChanged();
payRoll++;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
value = (String)adapter.getItem(position);
ListItem item = itemList.get(position);
Bundle info = new Bundle();
info.putString("val", value);
info.putInt("hours", item.getHours());
info.putInt("wage", item.getWages());
info.putInt("pos", position);
if(itemList.size() > 0)
{
for (ListItem items : itemList)
{
rollList.add(items.getPayroll());
hourList.add(items.getHours());
wageList.add(items.getWages());
}
}
info.putIntegerArrayList("rolls", rollList);
info.putIntegerArrayList("hours", hourList);
info.putIntegerArrayList("wages", wageList);
info.putInt("roll", payRoll);
info.putBoolean("rest", restore);
mainToPayroll.putExtras(info);
startActivity(mainToPayroll);
}
});
}
This Activity is started whenever an item on the listview is clicked
public class PayrollActivity extends AppCompatActivity
{
private static TextView text;
private String payrollNumber;
private int payrollHrs;
private int payrollWages;
private int position;
private Intent payrollToMain;
private Button returnButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payroll);
final Bundle info = getIntent().getExtras();
System.out.print(getIntent().getType());
payrollNumber = info.getString("val");
payrollHrs = info.getInt("hours");
payrollWages = info.getInt("wage");
position = info.getInt("pos");
payrollToMain = new Intent(this, MainActivity.class);
returnButton = (Button) findViewById(R.id.btnRtrn);
returnButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Bundle thing = new Bundle();
thing.putIntegerArrayList("rolls", info.getIntegerArrayList("rolls"));
thing.putIntegerArrayList("hours", info.getIntegerArrayList("hours"));
thing.putIntegerArrayList("wages", info.getIntegerArrayList("wages"));
thing.putInt("roll", info.getInt("roll"));
thing.putBoolean("rest", info.getBoolean("rest"));
payrollToMain.putExtras(thing);
startActivity(payrollToMain);
}
});
text = (TextView) findViewById(R.id.title);
text.setText(payrollNumber);
}
public static void setLabelText(String val)
{
text.setText(val);
}
This is a class I created for the items that go on the listview
public class ListItem
{
private int payroll;
private int hrs;
private int wages;
public ListItem(int roll, int hours, int wag)
{
payroll = roll;
hrs = hours;
wages = wag;
}
public int getPayroll()
{
return payroll;
}
public int getHours()
{
return hrs;
}
public int getWages()
{
return wages;
}
public void setPayroll(int roll)
{
payroll = roll;
}
public void setHrs(int hours)
{
hrs = hours;
}
public void setWages(int wage)
{
wages = wage;
}
public String toString()
{
return "Payroll " + payroll + "\n" + hrs + " hours\n$" + wages;
}
I think your problem is this piece of code in your MainActivity:
Bundle bun = getIntent().getExtras();
if(bun != null)
{
rollList = bun.getIntegerArrayList("rolls");
hourList = bun.getIntegerArrayList("hours");
wageList = bun.getIntegerArrayList("wages");
payRoll = bun.getInt("roll");
}
The getIntent().getExtras() may return a non-null Bundle object but the bundle may not have the keys you are trying to access, in which case all your instance variables will be set to null or zero for int.
You can get around this by simply checking if a particular key exists in the bundle and only setting your variable if it does.
bun.containsKey()
Or you can initialize your variables if they are null after loading them from the bundle.
Try uninstalling the app completely from the device and then try again. This solves the issue at times.
I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);
I am populating a Scrollview using items retrieved from a SQLite database, and am dynamically generating an OnClickListener for each row using the code below. I want the code in the OnClickListener to return control to the Activity which called it (MealActivity) using an Intent, passing back the id of the item which was clicked on.
I've attempted this using the 2nd code segment below, but I'm getting a compile error: "The method startActivity(Intent, int) is undefined for the type OnClickListenerSelectPresetItem".
How can I invoke the original Activity from my OnClickListener?
public class SelectPresetItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_preset_item);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
readRecords();
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<preset_item> preset_item = new TableControllerPresetItem(this).read();
if (preset_item.size() > 0) {
for (preset_item obj : preset_item) {
long id = obj.id;
String PresetDesc = obj.preset_desc;
int PresetMinutes = obj.preset_minutes;
String textViewContents = PresetDesc + " - "
+ PresetMinutes + " minutes";
TextView textViewItem = new TextView(this);
textViewItem.setPadding(0, 10, 0, 10);
textViewItem.setText(textViewContents);
textViewItem.setTag(Long.toString(id));
textViewItem.setOnClickListener(new OnClickListenerSelectPresetItem());
linearLayoutRecords.addView(textViewItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}listener
The method startActivity(Intent, int) is undefined for the type OnClickListenerSelectPresetItem
public class SelectPresetItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_preset_item);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
readRecords();
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<preset_item> preset_item = new TableControllerPresetItem(this).read();
if (preset_item.size() > 0) {
for (preset_item obj : preset_item) {
long id = obj.id;
String PresetDesc = obj.preset_desc;
int PresetMinutes = obj.preset_minutes;
String textViewContents = PresetDesc + " - "
+ PresetMinutes + " minutes";
TextView textViewItem = new TextView(this);
textViewItem.setPadding(0, 10, 0, 10);
textViewItem.setText(textViewContents);
textViewItem.setTag(Long.toString(id));
textViewItem.setOnClickListener(new OnClickListenerSelectPresetItem());
linearLayoutRecords.addView(textViewItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
This is the OnCLickListener code:
public class OnClickListenerSelectPresetItem implements OnClickListener {
public final static String EXTRA_MEAL_ID = "com.ian.mealtimer.MEAL_ID";
#Override
public void onClick(View view) {
Long selectedMealId = Long.valueOf(view.getTag().toString());
Intent myIntent = new Intent(view.getContext(),
MealActivity.class);
long mealId = -1;
myIntent.putExtra(EXTRA_MEAL_ID, selectedMealId);
startActivity(myIntent, 0);
}
}
You should use:
startActivity (Intent intent)
there is a different method which has an integer parameter:
startActivityForResult (Intent intent, int requestCode)
Also a context can start an activity, so you have to get the context. Easily you can get it from your view:
#Override
public void onClick(View view) {
Long selectedMealId = Long.valueOf(view.getTag().toString());
Intent myIntent = new Intent(view.getContext(),
MealActivity.class);
long mealId = -1;
myIntent.putExtra(EXTRA_MEAL_ID, selectedMealId);
view.getContext().startActivity(myIntent);
}
You can read more about starting activities here.
startActivity is a method of the class Context. The OnClickListener cannot know on which context it should be called. Pass the Context as Parameter to the constructor of the OnClickListener and save it inside:
In class OnClickListenerSelectPresetItem:
private Context context;
public OnClickListenerSelectPresetItem(Context context){
this.context=context;
}
Then call startActivity on this context
this.context.startActivity(myIntent, 0);
And construct them by passing the activity
textViewItem.setOnClickListener(new OnClickListenerSelectPresetItem(this));
How about you pass the activity to the constructor of the OnClickListenerSelectPresetItem
and then use it like the following :
public class OnClickListenerSelectPresetItem implements OnClickListener {
public final static String EXTRA_MEAL_ID = "com.ian.mealtimer.MEAL_ID";
private SelectPresetItemActivity selectPresetItemActivity;
public OnClickListenerSelectPresetItem(SelectPresetItemActivity selectPresetItemActivity){
this.selectPresetItemActivity = selectPresetItemActivity;
}
#Override
public void onClick(View view) {
Long selectedMealId = Long.valueOf(view.getTag().toString());
Intent myIntent = new Intent(view.getContext(),
MealActivity.class);
long mealId = -1;
myIntent.putExtra(EXTRA_MEAL_ID, selectedMealId);
selectPresetItemActivity.startActivity(myIntent, 0);
}
}
I have a TextView which contains a processed text, so that it will be in lower case and doesn't have punctuations.
Now I want to remove the stop words (these stop words are in my language which I already define). After that, I want to send the result to another TextView.
This my code
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button6) {
Intent i2 = new Intent(this, PreposisiRemoval.class);
String test = ((TextView) findViewById(R.id.textView7)).getText()
.toString();
String[] preposisi = { "akibat", "atas", "bagai", "bagi", "berkat",
"dalam", "dari", "demi", "dengan", "di", "hingga",
"karena", "ke", "kecuali", "lewat", "oleh", "pada",
"sampai", "sejak", "seperti", "tanpa", "tentang", "untuk" };
StringBuilder result = new StringBuilder();
Scanner fip1 = new Scanner(test);
while (fip1.hasNext()) {
int flag = 1;
String s1 = fip1.next();
for (int i = 0; i < preposisi.length; i++) {
if (s1.equals(preposisi[i])) {
flag = 0;
}
if (flag != 0) {
System.out.println(s1);
result.append(s1);
}
i2.putExtra("result2", result.toString());
startActivity(i2);
}
}
}
}
After I pressed button6, I did not get any results.
Where is the part of my coding that is wrong?
This code is in another Activity which will receive the processed text.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preposisi_removal);
Intent intent = getIntent();
String result = intent.getStringExtra("result2");
TextView tv = (TextView) findViewById(R.id.textView8);
tv.setMovementMethod(new ScrollingMovementMethod());
tv.setText(result);
tv.setTextSize(12);
}
To prepare the text for result2 you can try the following-
String STOP_WORD = "."; // define your stop word here.
String result2= result.replace(STOP_WORD ,"");
Then pass the text and set it on your second TextView.