I'm a beginner to android programming and I'm trying make a simple Rock, Paper, Scissors app. Right now I have three buttons (rock, paper, and scissors). When the user presses them, the computer randomly picks rock, paper, or scissors and then compares them to see if the user won. If the user won, then I want the score counter to in the upper right corner of the screen to increment by 1. At first I tried to initialize int scoreCount outside of the onCreate method which resulted in the app not being able to start up. Right now, I'm getting a null pointer exception inside my upScore method where I'm trying to use setText to update my TextView with the newest scoreCount. Below is my code. Thanks for any help that you can provide! Let me know if you need additional info! I'm really stuck on this!
import android.app.DialogFragment;
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.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int scoreCount;
TextView scoreView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreCount = 0;
TextView scoreView = (TextView) findViewById(R.id.score);
scoreView.setText("Score: " + scoreCount);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void outcome(View view){
//This function will determine whether the user picked Rock, Paper, or Scissors
//and then randomly have the computer pick Rock, Paper, or Scissors. A dialog will then
//generate to let the user know whether they won or lost.
String[] rpsArray = {"Rock","Paper","Scissors"};
int index = new Random().nextInt(rpsArray.length);
String cpuChoice = rpsArray[index];
String message = "";
int id = view.getId();
switch(id){
case R.id.rock_button:
if(cpuChoice.equals("Rock")){
//Tie
message = "The Computer picked Rock! It's a Tie!";
}
else if(cpuChoice.equals("Paper")){
//You Lose
message = "The Computer picked Paper! You Lose!";
}
else if(cpuChoice.equals("Scissors")){
//You win
message = "The Computer picked Scissors! You Win!";
upScore();
}
break;
case R.id.paper_button:
if(cpuChoice.equals("Paper")){
//Tie
message = "The Computer picked Paper! It's a Tie!";
}
else if(cpuChoice.equals("Scissors")){
//You Lose
message = "The Computer picked Scissors! You Lose!";
}
else if(cpuChoice.equals("Rock")){
//You win
message = "The Computer picked Rock! You Win!";
upScore();
}
break;
case R.id.scissors_button:
if(cpuChoice.equals("Scissors")){
//Tie
message = "The Computer picked Scissors! It's a Tie!";
}
else if(cpuChoice.equals("Rock")){
//You Lose
message = "The Computer picked Rock! You Lose!";
}
else if(cpuChoice.equals("Paper")){
//You win
message = "The Computer picked Paper! You Win!";
upScore();
}
break;
}
DialogFragment dialog = WinOrLoseDialog.newInstance(message);
dialog.show(getFragmentManager(),"WinOrLose");
}
public void upScore(){
scoreCount++;
scoreView.setText("Score: " + scoreCount);
}
}
Here's my xml layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#color/dark_teal">
<Button
android:id="#+id/rock_button"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="#string/rock"
android:onClick="outcome" />
<Button
android:id="#+id/paper_button"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_below="#id/rock_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/paper"
android:onClick="outcome" />
<Button
android:id="#+id/scissors_button"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_below="#id/paper_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/scissors"
android:onClick="outcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/version"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/white" />
<TextView
android:id="#+id/score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#color/white"
android:textSize="25sp"
android:textStyle="bold" />
</RelativeLayout>
This line in onCreate() is causing all your trouble:
TextView scoreView = (TextView) findViewById(R.id.score);
Instead of initializing the property of your activity class, you are creating and initializing a local variable. Change this to:
this.scoreView = (TextVoew) findViewById(R.id.score);
Related
So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:onClick="save"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:onClick="list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
This is the XML for the second Activity which will be opened when the list button is clicked:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show"
android:scrollbars="horizontal|vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="63dp" />
<TextView
android:text="#string/list_of_saved_url_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:id="#+id/textView"
android:textColor="#color/colorAccent"
android:textSize="24sp" />
</RelativeLayout>
This is my main class:
public class MainActivity extends AppCompatActivity {
private EditText url;
private Button save;
ArrayList<String> addArray = new ArrayList<String>();
private Button list;
private ListView show1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
list = (Button)findViewById(R.id.btn_list);
show1 = (ListView)findViewById(R.id.show);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = url.getText().toString();
if(addArray.contains(getInput))
{
Toast.makeText(getBaseContext(), "URL already added to the list!", Toast.LENGTH_LONG).show();
}
else if(getInput == null || getInput.trim().equals(""))
{
Toast.makeText(getBaseContext(), "Input field is empty!", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
((EditText)findViewById(R.id.txtbox_website)).setText("");
}
}
});
}
public void list(View view) {
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent screen = new Intent(MainActivity.this, Activity2.class);
startActivity(screen);
}
});
}
#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;
}http://www.stackoverflow.com
return super.onOptionsItemSelected(item);
}
}
My save button and list button is not able to save and list the URLs entered by the user.
What should I add?
Thanks
1) Not Saving:
Currently you are storing data statically inside your addArray object. Which gets cleared when you close app.
I think better to use persist data storage. So you can retrieve already stored websites when app re-launched. (Like browser manages history). Available storage options
2) Not showing list:
You need to pass your current list of urls (i.e. addArray variable) in bundle when starting Activity2 And read that list inside Activity2 onCreate. Find here.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
You don't need this list adapter inside your main activity, You need to create it inside Activity2 and set this adapter in your listview.
I hope it will help you fix your issues.
I am developing an application only to validate the interaction between activities through intents.
I created 5 ImageButton with an image for each. Each button is a movie and if you click any of them, is directed to a new activity with the synopsis of the film. The activity with the synopsis, there is an "up navigation" that returns the MainActivity (home).
The way I developed left very extensive project since created six activities (main activity and 5 activities, one for each film) and 6 layouts. Also, my apk is to 1.5mb.
Could someone help me with suggestions for best practices for I minimize my code or how developed is correct and could be developed in a real application?
I appreciate!!!
My MainActivity
package luizugliano.com.br.appfilmes;
import android.content.Context;
import android.content.Intent;
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.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void onClickBtVideo01(View view){
Intent intent = new Intent(getContext(),ActivityVideo01.class);
startActivity(intent);
}
public void onClickBtVideo02(View view){
Intent intent = new Intent(getContext(),ActivityVideo02.class);
startActivity(intent);
}
public void onClickBtVideo03(View view){
Intent intent = new Intent(getContext(),ActivityVideo03.class);
startActivity(intent);
}
public void onClickBtVideo04(View view){
Intent intent = new Intent(getContext(),ActivityVideo04.class);
startActivity(intent);
}
public void onClickBtVideo05(View view){
Intent intent = new Intent(getContext(),ActivityVideo05.class);
startActivity(intent);
}
private Context getContext(){
return this;
}
#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);
}
}
My ActivityVideo01 (other activities have the same code so I only put this as an example)
package luizugliano.com.br.appfilmes;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class ActivityVideo01 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_video01);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(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 == android.R.id.home) {
//O método finish encerrará essa activity
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
My content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView android:text="Sinopse - Filmes" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="22dp"/>
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/layout_marginTop">
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton01"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:background="#drawable/btn_img_01"
android:onClick="onClickBtVideo01"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton02"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_02"
android:onClick="onClickBtVideo02"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton03"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_03"
android:onClick="onClickBtVideo03"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton04"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_04"
android:onClick="onClickBtVideo04"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton05"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_05"
android:onClick="onClickBtVideo05"/>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
My content_activity_video01.xml (other layout have the same code so I only put this as an example)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_activity_video01"
tools:context="luizugliano.com.br.appfilmes.ActivityVideo01">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Title Synopsis"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Synopsis"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_marginTop="51dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I suggest, that you have two activities, and both these activities will act as container activity for their respective fragments.
In your first activity's fragment have your buttons. In your second activity's fragment, play your movie.
Now when you click on the button, go from first activity's fragment to second activity's fragment. Use interfaces to communicate between your fragments.
This is the way i thought about it, if you have a better way please do share.
Instead Of taking five different activity just take single activity and replace textview's value dynamically on the click of your button.
Just marge the two xml file like that in content_main.xml create another relative layout(which is initially gone view) with height width match parent under the image button linear layout. When one image button is pressed then just gone the view of linear layout of image buttons and visible the textview relative layout and visible the back button of the up navigation. When user pressed the up navigation just gone the textview relative layout, gone the up navigation and visible the linear layout of image button.
you need not to create multiple activities to show synopsis from different films.
you need to create your synopsis activity like a template and pass information about selected film in intent.
now you can change the content of your activity depending upon the information you received from intent.
Basically, whenever you are copying the code you need to ask yourself do you really need to copy the code? almost all the time answer is NO and what you actually need to do is, think of ways you can reuse the code you are copying.
Implement onclicklisstener and use switch case to detect which button has been clicked, Use only one activity to display synopsis instead of four and use bundle along with Intent to send which synopsis has to be shown. Here is the code.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
case R.id.imageButton01:
//handle click for imgbutton1;
Intent intent = new Intent(getContext(),ActivityVideo.class);
//send which video should be played along with the intent. use bundle in ActivityVideo class to get this value.
intent.putExtra("Video name", "video1");
startActivity(intent);
case R.id.imageButton02:
//handle click for imgbutton2;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video2");
startActivity(intent);
case R.id.imageButton03:
//handle click for imgbutton3;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video3");
startActivity(intent);
case R.id.imageButton04:
//handle click for imgbutton4;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video4");
startActivity(intent);
}
}
Use ActivityVideo class instid of ActivityVideo01, 02 ......
ActivityVideo.java ->
public class ActivityVideo01 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_video01);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle extras = intent.getExtras();
String VideoName = extras.getString("Video Name");
// VideoName will be having the sent value.
if(VideoName == "video1"){
//code for what do you want to do when imagebutton1 is clicked
}elseif(VideoName == "video2"){
//code for what do you want to do when imagebutton2 is clicked
}elseif(VideoName == "video3"){
//code for what do you want to do when imagebutton3 is clicked
}elseif(VideoName == "video4"){
//code for what do you want to do when imagebutton4 is clicked
}
}
#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 == android.R.id.home) {
//O método finish encerrará essa activity
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hope it helps!
Hello i need Your help in displaying data from database in activity, ive been trying many things but have no idea how to do that. Im creating some kind of weather app. It has Data in Database on the device.
There is DataBaseHandler Class which returns List with all Spots.
public List<Spot> getUserSpotList(int id){
List<Spot> spotList = new ArrayList<Spot>();
String selectQuery = "SELECT " +SPOT_ID+","+ SPOT_NAME + ","+ SPOT_LATITUDE + ","+SPOT_LONGITUDE+","+SPOT_WIND_SPEED +","+SPOT_WEATHER_ICON+
" FROM " + TABLE_SPOT + " WHERE "+SPOT_USER_ID + "="+id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Spot spot = new Spot();
spot.setSpot_id(Integer.parseInt(cursor.getString(0)));
spot.setSpotName(cursor.getString(1));
spot.setSpotLatitude(cursor.getString(2));
spot.setSpotLongitude(cursor.getString(3));
spot.setWindSpeed(Double.parseDouble(cursor.getString(4)));
spot.setSpotWeatherIcon(cursor.getString(5));
// Adding User to list
spotList.add(spot);
} while (cursor.moveToNext());
}
return spotList;
}
And i Have Activity with listView xml in witch i want to display some stuff from the code above based on another relativelayout for one element.
SpotActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.mk.rcwindy.SpotActivity">
<ListView
android:id="#+id/listLajout"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:layout_weight="1"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And here is Relative layout for one element in the list view above.
I would like to connect SpotName from database with TextView id=SpotName, Windspeed from database with Windspeed Text View, and Display image in ImageView based on SpotWeatherIcon from database.
spotlista_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:id="#android:id/list">
<ImageView
android:id="#+id/SpotAvilabilityIcon"
android:layout_width="20dp"
android:layout_height="match_parent"
android:background="#color/green_apple"/>
<ImageView
android:id="#+id/WeatherIcon"
android:layout_width="70dp"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/WindSpeed"
android:scaleType="centerInside"
/>
<TextView
android:id="#+id/WindSpeed"
android:text=""
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/WindSpeedUnit"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
<TextView
android:text="m/s"
android:textSize="30dp"
android:id="#+id/WindSpeedUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/SpotAvilabilityIcon"
android:layout_toStartOf="#+id/WeatherIcon"
android:layout_toLeftOf="#+id/WeatherIcon"
android:layout_centerVertical="true">
<TextView
android:id="#+id/SpotName"
android:text=""
android:textSize="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
</FrameLayout>
</RelativeLayout>
And here is the code of activity SpotActivity
public class SpotActivity extends ActionBarActivity {
int loggedUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spot);
Intent intent = getIntent();
if (null != intent) {
loggedUserId = intent.getIntExtra("logged", 0);
}
String text = "logged user id = "+loggedUserId;
Toast t1 = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
t1.show();
}
public int userIdSender(){
return loggedUserId;
}
#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_spot, 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;
}
if (id== R.id.action_new){
Intent intent = new Intent(this, SpotAddActivity.class);
intent.putExtra("logged",loggedUserId);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Thanks for Help! I tried to do that and still have a big problems so now im asking for help. Its a school project im working at and that is the last thing i have to do to make the app work-Display stuff :D
You need to create an adapter for your ListView. I recommend you watch The World Of ListView.
All an adapter does is provide a view for each item in your data set. For cursor data, you should subclass CursorAdapter and implement the newView() and bindView() methods at the minimum.
What I am trying to do is to have a simple sms application. The user puts their name and number in, and chooses to toggle a boolean box, and the enter button creates an intent to open up the built in sms and create a message according to the inputs.
What I'm having issues with is resetting the forms when I bring the application up again. Idealy I would like to have the entire application RESTART if you will, but Im not too sure how that works.
I was told to use:
editText.setText("");
to bring the fields to be null again, but eclipse isn't kind to me.
So my question is, how do I change my main_activity file with the code above to clear the edit text forms upon button press.
public class MainActivity extends Activity {
public boolean sexybox = false;
public void sexyBoolean(View view){ // changes the value from true to false etc
if(sexybox == false)
{
sexybox = true;
}
else
{
sexybox = false;
}
}
/** Called when the user clicks the Send button */
public void sendText(View view) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
//gives me user and number to be used.
EditText username = (EditText) findViewById(R.id.edit_name);
EditText usernumber = (EditText) findViewById(R.id.edit_number);
String usernamestring = username.getText().toString();
String usernumberstring = usernumber.getText().toString();
//checks if its null fields:
if(usernamestring.isEmpty())
{
Context context = getApplicationContext();
CharSequence text = "What's your name?";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.CYAN);
toast.show();
return;
}
if(usernumberstring.isEmpty())
{
Context context = getApplicationContext();
CharSequence text = "What's your numbah?";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.CYAN);
toast.show();
return;
}
///
System.out.println("SENDING MESSAGE:");
System.out.println(usernamestring);
System.out.println(usernumberstring);
String body = "Hi Jake - I'm " + usernamestring + "! I'm sending a self text so we can talk or whatever. ";
//IF CUTE button toggled
if(sexybox == true)
{
body = body + "I think you're hot too ;)";
}
smsIntent.putExtra("sms_body", body); //obvi the message
smsIntent.putExtra("address", usernumberstring); //obvi the number, replace usernumberstring
smsIntent.setType("vnd.android-dir/mms-sms"); // guess i leave this alone
//RESET FIELDS ????
// EditText edit_name = (EditText) findViewById(R.id.edit_name);
// edit_name.setText("");
// editText.setText("");
//editText.setText(null);
startActivity(smsIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
}
// XML:
<TextView
android:id="#+id/toptext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#303030"
android:text="#string/toptext"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#33B5E5"
android:textSize="50sp" />
<TextView
android:id="#+id/toptext2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#303030"
android:text="#string/toptext2"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#33B5E5" />
<EditText
android:id="#+id/edit_name"
android:layout_width="match_parent"
android:layout_height="75dp"
android:ems="10"
android:hint="#string/edit_name" />
<EditText
android:id="#+id/edit_number"
android:layout_width="match_parent"
android:layout_height="137dp"
android:ems="10"
android:hint="#string/edit_number"
android:inputType="phone" />
<TextView
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:text="#string/thanks"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#33B5E5" />
<CheckBox
android:id="#+id/sexycheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sexyBoolean"
android:text="#string/sexycheckbox" />
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#303030"
android:onClick="sendText"
android:text="#string/button_send"
android:textColor="#android:color/white" />
</LinearLayout>
Ok, I've implemented a android datagrid that amongst other things, lets you drag and drop columns around. This functionality works beautifully (better than I expected).
I noticed recently that if the grids were placed in tabcontents... it seems like zindex isnt taken into account (even though my ACTION_DRAG_STARTED will return false for column headers further back in the z-index, I still see those column headers responding to some events (like ACTION_DRAG_EXITED).
Attempting to have a controlled environment, I went ahead and built a stand alone project that demonstrates this problem.
I am hoping its something simple I missed, or perhaps ideas on how to work around it. Pretty simple to reproduce... run project, drag buttons around with long press... change tabs, drag those around, change back to first tab, drag around. It should start drag process, but as soon as you drag out of the control you were just in, you see "Reporting drop result:false".
Any pointers would be greatly appreciated... I suspect the underlying views are cancelling the drag event.
BrokeDragNDropActivity.java
package cm.mc.busteddnd;
import android.app.Activity;
import android.content.ClipData;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.View.OnLongClickListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;
public class BrokeDragNDropActivity extends Activity {
public static int selectedTab =0;
Extendedbutton button1;
Extendedbutton button2;
Extendedbutton button3;
Extendedbutton button4;
Extendedbutton button5;
Extendedbutton button6;
Extendedbutton button7;
Extendedbutton button8;
Extendedbutton button9;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final TabHost tabs = (TabHost) this.findViewById(R.id.my_tabhost);
tabs.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
selectedTab = tabs.getCurrentTab();
Log.i("***Selected Tab", "Im currently in tab with index::" + tabs.getCurrentTab());
}
});
tabs.setup();
TabSpec tspec1 = tabs.newTabSpec("First Tab");
tspec1.setIndicator("One");
tspec1.setContent(R.id.content);
tabs.addTab(tspec1);
TabSpec tspec2 = tabs.newTabSpec("Second Tab");
tspec2.setIndicator("Two");
tspec2.setContent(R.id.content2);
tabs.addTab(tspec2);
TabSpec tspec3 = tabs.newTabSpec("Third Tab");
tspec3.setIndicator("Three");
tspec3.setContent(R.id.content3);
tabs.addTab(tspec3);
//wire up buttons
button1 = (Extendedbutton)findViewById(R.id.button1);
button2 = (Extendedbutton)findViewById(R.id.button2);
button3 = (Extendedbutton)findViewById(R.id.button3);
button4 = (Extendedbutton)findViewById(R.id.button4);
button5 = (Extendedbutton)findViewById(R.id.button5);
button6 = (Extendedbutton)findViewById(R.id.button6);
button7 = (Extendedbutton)findViewById(R.id.button7);
button8 = (Extendedbutton)findViewById(R.id.button8);
button9 = (Extendedbutton)findViewById(R.id.button9);
//wire up listeners
button1.setGroup(1);
wireListeners(button1);
button2.setGroup(1);
wireListeners(button2);
button3.setGroup(1);
wireListeners(button3);
button4.setGroup(2);
wireListeners(button4);
button5.setGroup(2);
wireListeners(button5);
button6.setGroup(2);
wireListeners(button6);
button7.setGroup(3);
wireListeners(button7);
button8.setGroup(3);
wireListeners(button8);
button9.setGroup(3);
wireListeners(button9);
}
public void wireListeners(Extendedbutton button){
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View paramView) {
Extendedbutton v = (Extendedbutton)paramView;
ClipData data = ClipData.newPlainText("group_"+v.getGroup(), v.getDesc());
paramView.startDrag(data, // the data to be dragged
new View.DragShadowBuilder(paramView), // the drag shadow builder
null, // no need to use local data
0 // flags (not currently used, set to 0)
);
return true;
}
});
button.setOnDragListener(new OnDragListener(){
#Override
public boolean onDrag(View v, DragEvent event) {
// Defines a variable to store the action type for the incoming event
final int action = event.getAction();
// Handles each of the expected events
CharSequence dragData;
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
// Determines if this View can accept the dragged data
if (event.getClipDescription().getLabel().equals("group_"+(selectedTab+1))) {
// As an example of what your application might do,
// applies a blue color tint to the View to indicate that it can accept
// data.
v.setBackgroundColor(Color.BLUE);
// Invalidate the view to force a redraw in the new tint
v.invalidate();
// returns true to indicate that the View can accept the dragged data.
return(true);
} else {
// Returns false. During the current drag and drop operation, this View will
// not receive events again until ACTION_DRAG_ENDED is sent.
return(false);
}
case DragEvent.ACTION_DRAG_ENTERED: {
// Applies a green tint to the View. Return true; the return value is ignored.
v.setBackgroundColor(Color.GREEN);
// Invalidate the view to force a redraw in the new tint
v.invalidate();
return(true);
}
case DragEvent.ACTION_DRAG_LOCATION:
// Ignore the event
return(true);
case DragEvent.ACTION_DRAG_EXITED:
// Re-sets the color tint to blue. Returns true; the return value is ignored.
v.setBackgroundColor(Color.BLUE);
// Invalidate the view to force a redraw in the new tint
v.invalidate();
return(true);
case DragEvent.ACTION_DROP:
// Gets the item containing the dragged data
ClipData.Item item = event.getClipData().getItemAt(0);
// Gets the text data from the item.
dragData = item.getText();
// Displays a message containing the dragged data.
Toast.makeText(BrokeDragNDropActivity.this, "Dragged data is " + dragData, Toast.LENGTH_LONG);
// Turns off any color tints
v.setBackgroundColor(Color.BLACK);
// Invalidates the view to force a redraw
v.invalidate();
// Returns true. DragEvent.getResult() will return true.
return(true);
case DragEvent.ACTION_DRAG_ENDED:
// Turns off any color tinting
v.setBackgroundColor(Color.BLACK);
// Invalidates the view to force a redraw
v.invalidate();
// Does a getResult(), and displays what happened.
if (event.getResult()) {
Toast.makeText(BrokeDragNDropActivity.this, "The drop was handled.", Toast.LENGTH_LONG);
} else {
Toast.makeText(BrokeDragNDropActivity.this, "The drop didn't work.", Toast.LENGTH_LONG);
};
// returns true; the value is ignored.
return(true);
// An unknown action type was received.
default:
Log.e("DragDrop Example","Unknown action type received by OnDragListener.");
return false;
}
}
});
}
}
ExtendedButton.java (needed this to handle the group filtering)
package cm.mc.busteddnd;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
public class Extendedbutton extends Button {
private int group;
private String desc;
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Extendedbutton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public Extendedbutton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public Extendedbutton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
}
and finally...
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="65px"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="200px"
android:paddingTop="65px">
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal">
<cm.mc.busteddnd.Extendedbutton android:text="Button1" android:id="#+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
<cm.mc.busteddnd.Extendedbutton android:text="Button2" android:id="#+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
<cm.mc.busteddnd.Extendedbutton android:text="Button3" android:id="#+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
</LinearLayout>
<LinearLayout
android:id="#+id/content2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal">
<cm.mc.busteddnd.Extendedbutton android:text="Button4" android:id="#+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
<cm.mc.busteddnd.Extendedbutton android:text="Button5" android:id="#+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
<cm.mc.busteddnd.Extendedbutton android:text="Button6" android:id="#+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
</LinearLayout>
<LinearLayout
android:id="#+id/content3"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal">
<cm.mc.busteddnd.Extendedbutton android:text="Button7" android:id="#+id/button7" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
<cm.mc.busteddnd.Extendedbutton android:text="Button8" android:id="#+id/button8" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
<cm.mc.busteddnd.Extendedbutton android:text="Button9" android:id="#+id/button9" android:layout_width="wrap_content" android:layout_height="wrap_content"></cm.mc.busteddnd.Extendedbutton>
</LinearLayout>
</FrameLayout>
</TabHost>