I'm kinda new to android and I've been having a problem with the scanner class especially the .newline() since I can not get it to work in the following code java just scans everything in the document without checking the line
package com.cal.omida.calupdater;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
private TextView textv;
private Button submitButton;
private String TAG = "got here";
private String[] stringsarray = {"empty","empty","empty","empty","empty","empty","empty","empty","empty","empty","empty"};
private String exp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
textv = (TextView) findViewById(R.id.mainentry);
submitButton = (Button) findViewById(R.id.process);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String temp = textv.getText().toString();
String main = removeTab(temp);
Scanner scanner = new Scanner(main);
String[] finalString = scannerclass(scanner);
Log.d("found", main);
for (int io = 0; io<11;io++){
exp+=finalString[io]+"\n";
}
alert(exp,scanner);
}
});
}
private String[] scannerclass(Scanner scanner){
scanner.useDelimiter(";");
int i = 0;
while (scanner.hasNext()) {
String text = scanner.next();
stringsarray[i] = text;
i++;
}
return stringsarray;
}
private void alert(String text, final Scanner scanner){
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(text);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Add to cal",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//todo add to cal function
exp=null;
if (scanner.hasNextLine()){
scanner.nextLine();
String[] finalString = scannerclass(scanner);
for (int io = 0; io<11;io++){
exp+=finalString[io]+"\n";
}
alert(exp,scanner);
}
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
exp=null;
}
});
alertDialog.show();
}
private String removeTab(String main) {
String main2 = main.replace("\t",";");
return main2;
}
#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);
}
}
just to clarify my code a bit: I have an 11 part line separated by ";" I want to scan each part of the line put it into an array check the data using an alert dialog and if positive adding it to my calendar (still in development) and scan the next line.
my problem: if I enter less than 11 parts scanner continues to the next line. is there any way to stop this so it just scans the line that it's on and not continue to the next one?
The solution to this is to use one scanner to get each line, then a second scanner to separate each line.
For example:
String main = /*something*/;
Scanner lineScanner = new Scanner(main); // will scan each line, separated by a newline
while(lineScanner.hasNextLine()){
Scanner semicolonSeparatedScanner = new Scanner(lineScanner.nextLine());
/* work from here */
}
Mind, you could even simplify your code further, using String.split:
while(lineScanner.hasNextLine()){
String[] semicolonSeparatedText = lineScanner.nextLine().split(";");
}
Related
I am new to Android Studio. I am trying to use a ListView where the user can add items to a list. But when the user changes or closes the activity I want the items to come back as they were the last time the user saw them. I am not too familiar with the activity LifeCycle and how to use it yet so any resource or help is appreciated. Thanks. Here is my code:
package com.example.listviewtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity<i> extends AppCompatActivity {
private List nameArr;
private String textToAdd;
//input textbox
private EditText stuff;
// Add player names and scores to the list
private ListView score_lv;
//Append
private ArrayAdapter<String> arrayAdapter1;
//Clear Scores button
private Button updateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nameArr = new ArrayList<Object>();
stuff = (EditText)findViewById(R.id.editText);
score_lv = (ListView) findViewById(R.id.theList);
arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArr);
updateButton = (Button) findViewById(R.id.addButton);
updateButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
nameArr.add(stuff.getText().toString());
//get data from other activity
textToAdd = getIntent().getExtras().getString("textData");
score_lv.setAdapter(arrayAdapter1);
}
});
final Button nextAct = (Button) findViewById(R.id.toNext);
nextAct.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, Main2Activity.class);
startActivity(j);
}
}
);
}
#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);
}
}
Edit:
I was able to get the List updated using FileInputStream and FileOutputStream (I am trying to write to the Internal Storage). Because this app has 2 activites, when I switch to the other activity and go back to this one, the List and all its items remain. However, when I close the app entirely and then reopen the app, it seems that all the items in the list disappear. How do I make it stay using the FileI/OStreams (I know there is other methods like SQLite and such but I am trying to challenge myself by using other methods). Here is my updated code so far (thanks again to all for all of your help):
package com.example.listviewtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity<i> extends AppCompatActivity {
private static final List nameArr = new ArrayList<Object>();
//input textbox
private EditText stuff;
// Add player names and scores to the list
private ListView score_lv;
//Append
private ArrayAdapter<String> arrayAdapter1;
//Clear Scores button
private Button updateButton;
private static final String fileName = "scores";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
stuff = (EditText)findViewById(R.id.editText);
score_lv = (ListView) findViewById(R.id.theList);
arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArr);
score_lv.setAdapter(arrayAdapter1);
//button to update the ListView
updateButton = (Button) findViewById(R.id.addButton);
updateButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
//write data to the internal phone app File
try{
FileOutputStream fileOS = openFileOutput("scores", MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fileOS);
try{
osw.write(stuff.getText().toString());
osw.flush();
osw.close();
Toast.makeText(getBaseContext(),"Scores Saved to "+getFilesDir() + "/", Toast.LENGTH_LONG).show();
}catch(IOException e){
e.printStackTrace();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
//read data from Saved File to update the ListView
nameArr.add(readFile("scores"));
score_lv.setAdapter(arrayAdapter1);
}
});
//button to go to the next Activity
final Button nextAct = (Button) findViewById(R.id.toNext);
nextAct.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, Main2Activity.class);
startActivity(j);
}
}
);
}
//as soon as this Activity starts, we read from the Output File
public String readFile(String file){
StringBuilder text = new StringBuilder();
try{
FileInputStream fis = openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while((line = reader.readLine()) != null){
text.append(line);
}
reader.close();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"Error reading file!",Toast.LENGTH_LONG).show();
}
return text.toString();
}
#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);
}
}
So I added a Clear button but I was able to save multiple lines in the "scores" file that I saved in the internal device storage. When I close the app or go to the other activity and go back to this MainActivity with the ListView the information remains (because it reads directly from the "scores" file). The only thing is that it updates the 1 and only ListView item. I used nameArr.clear(); to clear the ListView everytime and the nameArr.clear(); and text.append('\n'); to read and write to the file so that each Text Input by the User appears the way I want them to (as a list). So here is my final code:
public class MainActivity<i> extends AppCompatActivity {
private static final List nameArr = new ArrayList<Object>();
//input textbox
private EditText stuff;
// Add player names and scores to the list
private ListView score_lv;
//Append
private ArrayAdapter<String> arrayAdapter1;
//Clear Scores button
private Button updateButton;
private static final String fileName = "scores";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
stuff = (EditText)findViewById(R.id.editText);
score_lv = (ListView) findViewById(R.id.theList);
arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArr);
nameArr.clear();
nameArr.add(readFile(fileName));
score_lv.setAdapter(arrayAdapter1);
//button to update the ListView
updateButton = (Button) findViewById(R.id.addButton);
updateButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
//write data to the internal phone app File
try{
FileOutputStream fileOS = openFileOutput(fileName, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOS);
try{
osw.write("\n");
osw.write(stuff.getText().toString());
osw.flush();
osw.close();
Toast.makeText(getBaseContext(),"Scores Saved to "+getFilesDir() + "/", Toast.LENGTH_LONG).show();
}catch(IOException e){
e.printStackTrace();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
//read data from Saved File to update the ListView with ALL items from the file
nameArr.clear();
nameArr.add(readFile(fileName));
score_lv.setAdapter(arrayAdapter1);
}
});
//button to go to the next Activity
final Button nextAct = (Button) findViewById(R.id.toNext);
nextAct.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, Main2Activity.class);
startActivity(j);
}
}
);
//delete file and clear ListView button
final Button clearB = (Button) findViewById(R.id.clearButton);
clearB.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
deleteFile(fileName);
Toast.makeText(getBaseContext(), "List Cleared", Toast.LENGTH_LONG).show();
//clear list
score_lv.setAdapter(null);
}
}
);
}
//as soon as this Activity starts, we read from the Output File
public String readFile(String file){
StringBuilder text = new StringBuilder();
try{
FileInputStream fis = openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while((line = reader.readLine()) != null){
text.append(line);
text.append('\n');
}
reader.close();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"Error reading file!",Toast.LENGTH_LONG).show();
}
return text.toString();
}
#rodgy, save your data to non-volatile memory, then read the data when you load the application.
try ths code
private List<String> nameArr = new ArrayList<>();
private static SharedPreferences sharedPreferences = context.getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
private static SharedPreferences.Editor editor = sharedPreferences.edit();
#how to use
// save data
setToList("1", nameArr);
// get data
nameArr = getList("1");
// save to sharedPreferences
public void setList(String key, List<String> list) {
String json = new Gson().toJson(list);
editor.putString(key, json);
editor.commit();
}
// read from sharedPreferences
public List<String> getList(String key){
List<String> result = new ArrayList<>();
String serObject = sharedPreferences.getString(key, null);
if (serObject != null){
Type type = new TypeToken<List<String>>(){}.getType();
result = new Gson().fromJson(serObject, type);
}
return result;
}
I recently wanted to develop a shopping list app and i followed this tutorial, but in this tutorial the tutor shows that his added items are stored but I followed the same process but when I close and reopen the app the added items are gone. what can be done to fix this?
here is my program code:
package com.dopenets.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import android.app.AlertDialog;
import android.widget.EditText;
import android.content.DialogInterface;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Activity;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.TextView;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ArrayList<String> shoppingList = null;
ArrayAdapter<String> adapter = null;
ListView lv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
shoppingList = getArrayVal(getApplicationContext());
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, shoppingList);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, final int position, long id) {
String selectedItem = ((TextView) view).getText().toString();
if (selectedItem.trim().equals(shoppingList.get(position).trim())) {
removeElement(selectedItem, position);
} else {
Toast.makeText(getApplicationContext(),"Error Removing Element", Toast.LENGTH_LONG).show();
}
}
});
}
#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();
if (id == R.id.action_add){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Item");
final EditText input = new EditText(this);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.add(preferredCase(input.getText().toString()));
Collections.sort(shoppingList);
lv.setAdapter(adapter);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public static String preferredCase(String original)
{
if (original.isEmpty())
return original;
return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase();
}
public static void storeArrayVal( ArrayList<String> inArrayList, Context context)
{
Set<String> WhatToWrite = new HashSet<String>(inArrayList);
SharedPreferences WordSearchPutPrefs = context.getSharedPreferences("dbArrayValues", Activity.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = WordSearchPutPrefs.edit();
prefEditor.putStringSet("myArray", WhatToWrite);
prefEditor.commit();
}
public static ArrayList getArrayVal( Context dan)
{
SharedPreferences WordSearchGetPrefs = dan.getSharedPreferences("dbArrayValues",Activity.MODE_PRIVATE);
Set<String> tempSet = new HashSet<String>();
tempSet = WordSearchGetPrefs.getStringSet("myArray", tempSet);
return new ArrayList<String>(tempSet);
}
public void removeElement(String selectedItem, final int position){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remove " + selectedItem + "?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.remove(position);
Collections.sort(shoppingList);
storeArrayVal(shoppingList, getApplicationContext());
lv.setAdapter(adapter);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
It appears that you are not calling the storeArrayVal method when an item is added, so nothing is ever stored.
I am working on an assignment for school, the instructions are to create a Bookmark app with two activities, one named BookNote which must be a List Activity and another called ManageActivity.
BookNote is to populate the List Activity on startup with data read from a file, if no file is present an example bookmark is created. Bookmarks can be added, edited, and deleted, but all typing must be done in ManageActivity. Whenever Booknote handles the data returned from ManageActivity it should alter the list.
The code I have now has comments showing my intentions for each function, but my current problem is that everytime I return to BookNote from ManageActivity, the app crashes with the error "Attempt to invoke virtual method 'void android.widget.ArrayAdapter.insert(java.lang.Object, int)' on a null object reference" when attempting to add or insert a new bookmark object into the ArrayAdapter.
BookNote Activity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class BookNote extends ListActivity{
private ArrayAdapter<Bookmark> adapter;
private final String FILENAME = "bookmarks.txt";
public String title = "EMPTY", url = "EMPTY", note = "EMPTY";
public String bookmarkClicked ="";
public int listViewID = 0;
public boolean intentListener = false;
public boolean addBookmarkClicked = false;
/*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity,
if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information
passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same
list element from which was chosen to edit.*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
addBookmarkClicked = false;
intentListener = false;
intentListener = getIntent().getBooleanExtra("listen", false);
if(intentListener == true) {
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
note = getIntent().getExtras().getString("note");
listViewID = getIntent().getExtras().getInt("listViewID");
Bookmark bookmark = new Bookmark(title,url,note);
Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show();
if(addBookmarkClicked == true) {
addBookmark(bookmark);
}
else {
insertBookmark(bookmark, listViewID);
}
//writeData();
}
}
//When list item is clicked, fill bookmarkClicked with values in list item, record item position, and call gotoManageActivity() to pass information to ManageActivity.
public void onListItemClick(ListView listView, View view, int position, long id) {
ListView myListView = getListView();
Object itemClicked = myListView.getAdapter().getItem(position);
Toast.makeText(getApplicationContext(), "Item clicked: " + itemClicked + "\nItem ID: " + id,Toast.LENGTH_SHORT).show();
bookmarkClicked = itemClicked.toString();
listViewID = position;
gotoManageActivity();
}
//reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt
private ArrayList<Bookmark> readData(){
ArrayList<Bookmark> bookmarks = new ArrayList<>();
try {
FileInputStream fis = openFileInput(FILENAME);
Scanner scanner = new Scanner(fis);
if (scanner.hasNext()){
String titleScan = scanner.nextLine();
String urlScan = scanner.nextLine();
String noteScan = scanner.nextLine();
Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan);
bookmarks.add(bookmark);
}else{
Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note");
bookmarks.add(bookmark);
}
scanner.close();
} catch (FileNotFoundException e) {
}
return bookmarks;
}
//If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
//writeData();
}
//If a list item is clicked, any edits will be inserted back into the ArrayAdapter in the same position of the item clicked.
private void insertBookmark(Bookmark bookmark, int listViewID){
adapter.insert(bookmark,listViewID);
//writeData();
}
//Calls ManageActivity and reports information about app.
public void gotoManageActivity(){
Intent manageIntent = new Intent(this, ManageActivity.class);
Bundle extras = new Bundle();
extras.putString("bookmark", bookmarkClicked);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
extras.putInt("listViewID", listViewID);
manageIntent.putExtras(extras);
startActivity(manageIntent);
}
#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_book_note, 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_add) {
addBookmarkClicked = true;
gotoManageActivity();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ManageActivity
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ManageActivity extends AppCompatActivity {
private String title = "EMPTY", url = "EMPTY", note = "EMPTY";
private boolean listener = true;
private boolean addBookmarkClicked = false;
/* When activity starts, check for addBookmarkClicked status, create book */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_layout);
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
String bookmarkString = "";
bookmarkString = getIntent().getExtras().getString("bookmark");
if(bookmarkString != null && bookmarkString.length() > 0) {
if (bookmarkString.length() != 0) {
String[] stringArray = bookmarkString.split("\\n");
title = stringArray[0];
url = stringArray[1];
note = stringArray[2];
updateTextViews();
}
}
else {
updateTextViews();
}
}
#Override
public void onBackPressed(){
Intent bookNoteIntent = new Intent(this, BookNote.class);
startActivity(bookNoteIntent);
Bundle extras = new Bundle();
extras.putString("title", title);
extras.putString("url", url);
extras.putString("note", note);
extras.putBoolean("listen", listener);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
bookNoteIntent.putExtras(extras);
startActivity(bookNoteIntent);
}
public void editButtonCall(View view){
showNoteDialog();
showURLDialog();
showTitleDialog();
}
public void webButton(View view){
if(url.length() != 0 && url != "EMPTY"){
}
}
public void updateTextViews(){
TextView titleTextView = (TextView) findViewById(R.id.titleTV);
TextView urlTextView = (TextView) findViewById(R.id.urlTV);
TextView noteTextView = (TextView) findViewById(R.id.noteTV);
titleTextView.setText("Title: " + title);
urlTextView.setText("URL: " + url);
noteTextView.setText("Note: " + note);
}
//Show dialog and editText for user to assign title to bookmark.
public void showTitleDialog(){
AlertDialog.Builder titleBuilder = new AlertDialog.Builder(this);
titleBuilder.setTitle("Enter Title");
final EditText titleET = new EditText(this);
titleET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
titleBuilder.setView(titleET);
titleBuilder.setPositiveButton("Add", newDialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
title = titleET.getText().toString();
updateTextViews();
}
});
titleBuilder.show();
}
//Show dialog and editText for user to assign note to bookmark.
public void showNoteDialog(){
AlertDialog.Builder noteBuilder = new AlertDialog.Builder(this);
noteBuilder.setTitle("Enter Note");
final EditText noteET = new EditText(this);
noteET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
noteBuilder.setView(noteET);
noteBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
note = noteET.getText().toString();
updateTextViews();
}
});
noteBuilder.show();
}
//Show dialog and editText for user to assign url to bookmark.
public void showURLDialog(){
AlertDialog.Builder urlBuilder = new AlertDialog.Builder(this);
urlBuilder.setTitle("Enter URL");
final EditText urlET = new EditText(this);
urlET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
urlBuilder.setView(urlET);
urlBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
url = urlET.getText().toString();
updateTextViews();
}
});
urlBuilder.show();
}
}
You are declaring a global and a local instance of adapter. In onCreate() method of BookNote Activity, remove the local instance. Change
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
to
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
You are not setting xml file which contains
book_layout.xml
<ListView android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_layout);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, 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);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.
i have just started with android but have done some c# which seems very similar to java
in short, the problem lies in the closeDialog method
I am not very familiar with view/viewgroup so please dont bombard me with incorrect usage of objects, etc.
in short, i am creating a simple app which i hope to improve on (it is basically the start of a huge project)
the _showhint dialog opens fine, and shows the "hint" as expected, but the closeDialog force closes the app, I have no idea why
package com.example.app;
import android.app.Activity;
import android.app.Dialog;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageImageURI = null;
private TextView lblAnswer, lblWelcome;
private EditText edtInput;
public TextView showText ;
public Button btnShowHint, btnCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtInput = (EditText) findViewById(R.id.edtInput) ;
lblWelcome = (TextView) findViewById(R.id.lblWelcome) ;
lblAnswer = (TextView) findViewById(R.id.lblAnswer) ;
btnShowHint = (Button) findViewById(R.id.btnHelp);
btnCalculate = (Button) findViewById(R.id.btnShow) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void calculate(View vw)
{
String [] arrEditStore = new String[edtInput.length()] ;
String arrOperators [] = {"+", "-", "*", "/", "(", ")"} ;
}
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
EDIT: ADDED "this" to final Dialog dialog = new Dialog(this)
I have discovered what has caused the problem
GIVEN CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
SOULTION
first, I moved the decleration of the btnClose to the top
public Button btnShowHint, btnCalculate, btnClose;
then in the design view, removed the link of the button Close onclick method refering to closeDialog.
Afterwards, removing the closeDialog method completely, and also moving some of that code to the _showHint method
it also makes logical sense, thanks to #Mike M. who commented on the post, helped me reason it out, since I say, THIS button must close the dialog but in the method of this button, I am assigning it to be used by itself, which doesn't make logical sense at all, here is the changed code and it works
CHANGED CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
btnClose = (Button) showHintDialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showHintDialog.dismiss();
}
});
}
We all make stupid and unnessasary mistakes at times, some worse than others, but if you find a solution to a problem you have had, maybe somewhere someone has the same issue, so post a solution to your problem, it might help that someone!!!
cheers