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;
}
Related
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(";");
}
I'm trying to do a chat application with two activities. On the first plan is a short list containing the last sent message in each row. A second activity contain all conversation. I use socket.io and my problem is that, when I click back button and then I come back to my app notifyDataSetChanged() stops working. My app recevie a messages from dialog box from a website which a cooperates with android app. In console log I see that a messages from a website are received and onTaskComplete() method is called but a listview is not refreshing. I read that an adapter loses a reference to a listview after restart an activity but how to see in my code I create a new adapter in onResume() method. I don't understand what I do wrong?
While if I will throw out beyond the condition "mSocket.on("message", onMessage);" then a listview is refresh after come back to app but a messages are multiple as many times as there were returns.
below is my code, please help!
MainActivity:
package com.example.seadog.fb_dialog;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends Activity implements MyListener {
public ListView listView;
public MyBaseAdapter adapter;
public TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Get Socket.io Object
*/
SocketIO socketIo = new SocketIO();
Socket mSocket = socketIo.getSocket(); // get socket
Integer id = socketIo.getId(); // get Website ID
if(mSocket == null) {
socketIo.Connection();
mSocket = socketIo.getSocket();
mSocket.on("message", onMessage);
}
listView = (ListView) findViewById(R.id.listView);
/*
* OnItemClickListener
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Conversation.class);
intent.putExtra("item", position);
startActivity(intent);
TextView textView = (TextView) view.findViewById(R.id.descitem);
textView.setTypeface(null, Typeface.NORMAL);
}
});
textView = (TextView) findViewById(R.id.count);
}
private Emitter.Listener onMessage = new Emitter.Listener() {
/*
* Message Listener
*/
#Override
public void call(Object... args) {
Boolean isset = false;
try {
JSONObject object = (JSONObject) args[0];
String _id = object.getString("_id");
String message = object.getString("message");
JSONObject obj = new JSONObject();
obj.put("direction", "fb-lt");
obj.put("message", message);
obj.put("date", "2017-05-29T12:15:49.245Z");
for(int i = 0; i < arrayList.size(); i++){
ListData ld = (ListData) arrayList.get(i);
String id = ld.getId();
if(_id.equals(id)){
JSONArray Data = ld.getData();
Data.put(obj);
ld.setDescription(message);
arrayList.set(i, ld);
isset = true;
Log.d("LOG", message);
}
}
if(!isset) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
ListData ld = new ListData();
ld.set_id(_id);
ld.setID(1);
ld.setTitle("Klient:");
ld.setDescription(message);
ld.setData(jsonArray);
arrayList.add(ld);
}
onTaskComplete();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
public void onResume() {
super.onResume();
ArrayList clone = (ArrayList) arrayList.clone();
arrayList.clear();
arrayList.addAll(clone);
adapter = new MyBaseAdapter(this, arrayList);
listView.setAdapter(adapter);
}
#Override
public void onTaskComplete() {
runOnUiThread(new Runnable() {
#Override
public void run () {
Log.d("LOG:","refresh");
adapter.notifyDataSetChanged();
}
});
}
}
Interface MyListener:
package com.example.seadog.fb_dialog;
import java.util.ArrayList;
public interface MyListener {
ArrayList arrayList = new ArrayList();
void onTaskComplete();
}
If I remember well, when you open a new activity in android, that's something separate from the previous one.
When you press the back button, it just kill the activity you were in and show the previous activity.
Maybe you can try to do what you need when back is pressed in this :
#Override
public void onBackPressed()
{
//Do your things here
}
Hope I helped.
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 am trying to create a main menu activity in android which dynamically selects the activity destination from its position on the page.
MainMenu.java
package com.verscreative.BowlTrack;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class MainMenu extends SherlockActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new HomeMenuAdapter());
gridview.setPadding(50, 40, 50, 40);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Activities That are invoked by the click
String[] mActivitiesIds = {
getString(R.string.menu_launch_0),
getString(R.string.menu_launch_1),
getString(R.string.menu_launch_2),
getString(R.string.menu_launch_3),
getString(R.string.menu_launch_4),
getString(R.string.menu_launch_5)
};
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
//TODO: Switch Toast To Activity Intent
Intent i = new Intent();
i.setClassName(packageName, className);
try{
startActivity(i);
}catch(Exception e){
Toast t = Toast.makeText(getApplicationContext(), "Cannot Find Activity", Toast.LENGTH_LONG);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
activateSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void activateSettings(){
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
public class HomeMenuAdapter extends BaseAdapter {
public HomeMenuAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(getApplicationContext());
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setPadding(0, 10, 0, 10);
} else {
tv = (TextView) convertView;
}
tv.setCompoundDrawablesWithIntrinsicBounds(0, mThumbIds[position], 0, 0);
tv.setText(mTextIds[position]);
tv.setHeight(300);
tv.setTextColor(Color.WHITE);
return tv;
}
// references to our images
private Integer[] mThumbIds = {
android.R.drawable.ic_menu_add,
android.R.drawable.ic_menu_view,
android.R.drawable.ic_menu_info_details,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_preferences
};
private String[] mTextIds = {
getString(R.string.menu_item_0),
getString(R.string.menu_item_1),
getString(R.string.menu_item_2),
getString(R.string.menu_item_3),
getString(R.string.menu_item_4),
getString(R.string.menu_item_5)
};
}
}
However whatever I do it always says "Cannot Find Activity".
If I change:
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
Intent i = new Intent();
i.setClassName(packageName, className);
to for example:
Context packageName = MainMenu.this;
Class<ViewGamesActivity> className = ViewGamesActivity.class;
Intent i = new Intent();
i.setClass(packageName, className);
It works fine, but all options do the same thing!
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BowlTrack</string>
<string name="action_settings">Settings</string>
<string name="menu_item_0">Add New Game</string>
<string name="menu_item_1">View Games</string>
<string name="menu_item_2">Stats</string>
<string name="menu_item_3">3-Not</string>
<string name="menu_item_4">4-Not</string>
<string name="menu_item_5">Settings</string>
<string name="menu_launch_0">NewGameActivity</string>
<string name="menu_launch_1">ViewGamesActivity</string>
<string name="menu_launch_2">ViewOverallActivity</string>
<string name="menu_launch_3">3-Not</string>
<string name="menu_launch_4">4-Not</string>
<string name="menu_launch_5">SettingsActivity</string>
<color name="black">#000000</color>
<color name="bwtk">#88078b</color>
<string name="title_activity_view_games">View Games</string>
</resources>
ViewGamesActivity.java
package com.verscreative.BowlTrack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class ViewGamesActivity extends SherlockActivity {
public class ViewGames extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static final String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_games);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
// TODO: Starting new intent
// Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
// in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response
// back
// startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGamesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// TODO: no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewGamesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME }, new int[] { R.id.pid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
Thanks to jimpanzer and sherif-elkhatib, I have combined your comments to find the answer.
The Answer is Changing:
String className = mActivitiesIds[position]+".class";
to this:
String className = "com.verscreative.BowlTrack."+mActivitiesIds[position];
I don't think you need to specify the .class
Try this
String className = mActivitiesIds[position];
Otherwise, a more efficient solution would be to have a 2D array as such :
Object[][] mActivitiesIds =
{
{ getString(R.string.menu_launch_0), Activity1.class }
{ getString(R.string.menu_launch_1), Activity1.class }
{ getString(R.string.menu_launch_2), Activity1.class }
{ getString(R.string.menu_launch_3), Activity1.class }
{ getString(R.string.menu_launch_4), Activity1.class }
{ getString(R.string.menu_launch_5) Activity1.class }
};
Then simply use mActivitiesIds[n][1] to get the class...