Android dynamic listview - java

I want to make a ListView that gets its elements(strings) from user input. I have a button that directs the user to another activity and while in it, the user enters a name and presses another button to come back to the original activity. The same button gets and adds a string to the ArrayAdapter that the ListView uses and displays it as an element in the ListView. It doesn't seem to work and I know it's a stupid mistake, but I'm fresh to android development and this in particular I haven't done before.
Here's all the code:
the MainActivity
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> simpleArray =new ArrayList<String>();
ListAdapter simpleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
simpleArray);
ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(simpleAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void enterActivity(View view) {
Intent toEnterSecond = new Intent(this, SecondActivity.class);
startActivity(toEnterSecond);
}
}
The second acitivity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import java.util.ArrayList;
public class SecondActivity extends Activity{
private EditText projectName;
ArrayList simpleArray;
ArrayAdapter simpleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
projectName = (EditText) findViewById(R.id.eTxt);
}
public void getBack(View view) {
String projectCalling = String.valueOf(projectName.getText());
simpleArray.add(projectCalling);
simpleAdapter.notifyDataSetChanged();
Intent comeBack = new Intent(this, MainActivity.class);
startActivity(comeBack);
}
}
And the layouts
<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"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/simpleButton"
android:text="click me plox"
android:onClick="enterActivity"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/simpleButton"
android:id="#+id/lv">
</ListView>
</RelativeLayout>
//
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Enter the name of your project:"
android:id="#+id/txt"/>
<EditText
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_below="#+id/txt"
android:id="#+id/eTxt"/>
<Button
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_below="#+id/eTxt"
android:text="click"
android:onClick="getBack"/>
</RelativeLayout>

Explanation:
You can start SecondActivity with startActivityForResult() instead of startActivity as answered here and in onResultActivity method you can call simpleAdapter.notifyDataSetChanged();. Don't call simpleAdapter.notifyDataSetChanged(); in SecondActivity.
To learn how to use startActivityForResult check this.
Also use finish() instead of
Intent comeBack = new Intent(this, MainActivity.class);
startActivity(comeBack);
in SecondActivity to go back to MainActivity.
Solution:
Change MainActivity enterActivity method to this:
...
public void enterActivity(View view) {
Intent toEnterSecond = new Intent(this, SecondActivity.class);
startActivityForResult(toEnterSecond,1);
}
Add this to end of SecondActivity getBack method:
MainActivity.simpleArray.add(projectCalling);
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
finish();
Finally add this new method to MainActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data{
if (requestCode == 1) {
if(resultCode == RESULT_OK){
((ArrayAdapter) simpleAdapter).notifyDataSetChanged();
}
}
}
To be able to access simpleAdapter, you need to define it outside of onCreate:
public class MainActivity extends ActionBarActivity {
private ListAdapter simpleAdapter;
public static ArrayList<String> simpleArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
simpleArray =new ArrayList<String>();
simpleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
simpleArray);
...
}

Related

Passing data between activities for a voting app

I am new to android programming and have ran into a problem. I am trying to create a voting app where when a user opens up the application and the MainActivity is shown, from here they press a button to go into the second Screen (Screen2) which shows images of people and their names as buttons. When a persons name (in a button on Screen2) is pressed , a text field shows the number of times the button is pressed in an another activity (Screen4) . The problem here is that when i try to show this (Screen4), the app crashes. I am quite new to this so if you didn't understand my issue or need more information please let me know. Any help is appreciated. Thank you.
EDIT : After some help I used Intent to try send the data across but now when when the button in screen2 is pressed the app refreshes and then takes me back to the mainActivity and when this process is tried again the app crashes.
This is the new Screen2 :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Screen2 extends AppCompatActivity {
TextView showValue;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
showValue = findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the On click for the Textview in a different activity.
}
public void AnCount(View v) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
public void ButtonToGoToTheOtherActivity(View v) {
Intent intent = new Intent(this, Screen4.class);
intent.putExtra("valueOfCounter", counter); //the code for sending data to the other activity.
startActivity(intent);
}
}
This is the XML for screen 2 :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Screen2">
<Button
android:id="#+id/AnnieBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:text="#string/annie_liou"
android:onClick="AnCount"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView5"
/>
This is my Screen4:
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Screen4 extends AppCompatActivity {
private Button Button3;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen4);
Button3 = (Button) findViewById(R.id.Button3);
Button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) { openActivity4();
}
}
);
counter = getIntent().getIntExtra("valueOfCounter", 0); // 0 is default value
}
public void openActivity4() {
Intent intent = new Intent(Screen4.this, MainActivity.class);
startActivity(intent);
}
}
Here is the XML for screen4:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/MainScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Screen4">
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="193dp"
android:layout_marginLeft="193dp"
android:layout_marginEnd="109dp"
android:layout_marginRight="109dp"
android:layout_marginBottom="660dp"
android:text="This is 4th screen"
android:textSize="32sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.664"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/Button3" // return to main screen
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="532dp"
android:text="Return"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
<TextView
android:id="#+id/VoteCountAnnie" // textview where i want the increment to show
android:layout_width="121dp"
android:gravity="center"
android:layout_height="52dp"
android:layout_marginStart="116dp"
android:layout_marginLeft="116dp"
android:layout_marginTop="82dp"
android:layout_marginEnd="174dp"
android:layout_marginRight="174dp"
android:text="0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my main Activity Screen (not used for the clicking but if there is something wrong in this that could affect the other Screens please let me know) :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openActivity3();
}
}
);
}
public void openActivity2() {
Intent intent = new Intent(this, Screen2.class);
startActivity(intent);
}
public void openActivity3() {
Intent intent = new Intent(this, Screen3.class);
startActivity(intent);
}
}
Here is the XML for screen 4:
This works same using intent .
Main Class :
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
count = savedInstanceState.getInt(EXTRA_VOTE_KEY);
}
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
/* Intent intent = new Intent(this,DisplayCount.class);
//intent.putExtras(intent);
startActivity(intent,bundle);*/
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
public void go(){
Intent intent = new Intent(this,DisplayCount.class);
intent.putExtra(EXTRA_VOTE_KEY,count);
startActivity(intent);
}
}
Activity of Main Class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout
Display Class :
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView;
private int count;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
Intent intent = getIntent();
count = intent.getIntExtra(MainActivity.EXTRA_VOTE_KEY,0);
textView.setText(Integer.toString(count));
}
}
Activity of display class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
Manifest :
include following in your manifest file :
<activity android: name =".DisplayCount"></activity>
add following to manifest :
// Main Activity //
- List item
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
}
public void go(){
DisplayCount.setVoteCount(count);
Intent intent = new Intent(this, DisplayCount.class);
startActivity(intent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
}
/** Class to display: **/
- List item
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView ;
private static int count ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
textView.setText(Integer.toString(count));`enter code here`
}
public static void setVoteCount(int c){
count = c;
}
}
/***** Activity files *****/
- List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
/**** Activity That display's ****/
-List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout>
As Mike M. said you are using id of a textview which is in a different activity. In android we cannot access ids of views in a different activity. We can only access ids of view in the same activity in which we are.
So that is for the error you are getting.
For accessing Data from another activity you can pass the data like this:
public class Screen2 extends AppCompatActivity {
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen1);
showValue = (TextView) findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the Id for the Textview in a different activity.
}
public void AnnieCountInc (View view) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
//make another button with a method like
public void ButtonToGoToTheOtherActivity(View view){
Intent intent =new Intent(this,Screen4.class);
intent.putExtra("valueOfCounter",counter); //the code for sending data to the other activity.
startActivity(intent);
}
Then in your Screen4 activity you can get the value of "counter" in the onCreate method by:
counter = getIntent().getIntExtra("valueOfCounter",0); // 0 is default value
This is one method.
You can also use a static variable to pass on data easily by defining your counter varaible as
public static int counter;
Then you can access it directly and it will show you the value.

in this program passing ArrayList from one activity to another not working

first activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button bt1;
private Button bt2;
private EditText ed1;
private EditText ed2;
private TextView tv3;
static ArrayList<String> s = new ArrayList<>();
static ArrayList<Integer> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
bt2 = (Button)findViewById(R.id.button2);
tv3 = (TextView)findViewById(R.id.textView3);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
s.add(ed1.getText().toString());
i.add(Integer.parseInt(ed2.getText().toString()));
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(MainActivity.this, second.class);
intent.putExtra("key", s);
startActivity(intent);
}
catch(Exception e) {
tv3.setText(e.getMessage());
}
}
});
}
}
Second activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.widget.TextView;
import java.util.ArrayList;
public class second extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = (ArrayList<String>)getIntent().getSerializableExtra("key");
for(int j=0;j<=s.size();j++) {
tv1.setText(s.get(j));
}
}
}
I don't understand the problem in this code. when I click on bt2 to pass the ArrayList from on activity to another then the app just shutdown. I am not able to understand the problem in this code.
Please help me,
I have also updated the manifest.xml for second class.
Are you sure
i.add(Integer.parseInt(ed2.getText().toString()));
in the onClick() call doesnt throw an Exception?
Use a try-catch block around your code in Listener.onClick().
Btw., you can easily use Lambda Exrpessions for ActionListeners.
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Please use following construct:-
While Sending:
intent.putStringArrayListExtra("key", s)
While Receiving:
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
Replace your for loop with below, use j< s.size and not j<=s.size
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
You can do like this :
Bundle info= new Bundle();
ArrayList<Product> mas = new ArrayList<Product>();
info.putSerializable("product", mas);
intent.putExtras(info);
And get the values with this:
ArrayList<Product> prod = getIntent().getSerializableExtra(key);
Product class like a serializable object
private class Product implements Serializable {
}
Here it is just how you can pass arraylist between activities.Hope you wil get an idea to solve your issues.
intent.putExtra("key", s);-- this is wrong, you are sending a string but not your arrayList
Try sending with-- intent.putStringArrayListExtra("key", s);
and receiving -- ArrayList<String> stringArray = getIntent().getStringArrayListExtra("key");
hope this will solve your problem...
In your second activity onCreate, add the following code:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// Add view
// Must add check extras if null.
Bundle extras = getIntent().getExtras();
ArrayList<String> s = extras.getStringArrayListExtra("key");
// do something
}
In your first activity, send intent with:
Intent intent = new Intent(MainActivity.this, second.class);
intent.putStringArrayListExtra("key", s);
startActivity(intent);
I've tried an sample app with your code. Hope this will help you.
Kindly check my codes.
First Activity
package com.arindam.testapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class FirstActivity extends AppCompatActivity {
Button bt1;
EditText ed1;
EditText ed2;
TextView tv3;
ArrayList<String> s = new ArrayList<>();
ArrayList<String> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
tv3 = (TextView)findViewById(R.id.textView);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
s.add(ed1.getText().toString());
i.add(ed2.getText().toString());
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("key", s);
intent.putExtra("value", i);
startActivity(intent);
}
catch(Exception e)
{
tv3.setText(e.getMessage());
}
}
});
}
}
First Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#679667"
android:orientation="vertical"
tools:context="com.arindam.testapp.FirstActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
</LinearLayout>
Second Activity
package com.arindam.testapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
ArrayList<String> i = getIntent().getStringArrayListExtra("value");
for(int k=0;k<i.size();k++)
{
tv2.setText(i.get(k));
}
}
}
Second Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#229597"
android:orientation="vertical"
tools:context="com.arindam.testapp.SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>
If you want to work with key value pairs, go for hashMap.

the codes are not working in the second xml file

i am just working on a test app.
this is the xml file of the home page.
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivityTEST2" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp"
android:text="Button12" />
</RelativeLayout>
i have added a button listener to go to other page. here is my code for that.
package com.example.test2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivityTEST2 extends Activity {
Button but;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_test2);
but=(Button)findViewById(R.id.button12);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
setContentView(R.layout.activity123);
}
});
}
#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_activity_test2, menu);
return true;
}
when i add a button listener in the second page to display text in the textfield, nothing works.
xml file of the second page
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<EditText
android:id="#+id/edittext1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
when i add a button listerner to display text in the textfiled, nothing works.
the app neighter stops working nor does anything after that.
my second window's java content is
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.test2.R;
public class activity_main_activty_test2 extends Activity {
Button but2;
EditText edit1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity123);
edit1=(EditText)findViewById(R.id.edittext1);
but2=(Button)findViewById(R.id.button2);
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edit1.setText("hellow");
}
});
}
#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_activity_test2, menu);
return true;
}
}
am i missing something. do i have to address something. please help i am just a biggener.
i have added a button listener to go to other page No, apparently you haven't.
You cannot go to the other activity through this code
setContentView(R.layout.activity123);
You need to use Intent
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivityTEST2.this,activity_main_activty_test2.class);
startActivity(intent);
finish(); //optional
}
ALSO remove import com.example.test2.R; from your second activity.
if you want to go to the next view, you dont use setContentView(R.layout.activity123); in your button listener it will not transfer you to the next activity, instead make use of intent since you have a 2nd activity.
Intent intent = new Intent(getBaseContext(), activity_main_activty_test2.class);
startActivity(intent)
in your MainActivityTEST2
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), activity_main_activty_test2.class);
startActivity(intent)
}
});
Please Change your first page as following. Android use Intent to jump the activity from one to another.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivityTEST2 extends Activity {
Button but;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_test2);
but = (Button) findViewById(R.id.button12);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(this, activity_main_activty_test2.class);
startActivity(intent);
finish();
}
});
}
#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_activity_test2, menu);
return true;
}
}

I got a nullpointerexception that I can't fix

Hi I'm attempting to code a Android app that has multiple things in it.
I'm having alot of trouble trying to get rid of this nullpoinerexception.
It crashes when I click on the button in the app.
Can anyone help please?
MainActivity.java:
package com.smoke.rms;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button button1, button2;
LinearLayout ourlayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button1 = visit_our_site
button1 = (Button) findViewById(R.id.button1);
// Button2 = youtube_button
button2 = (Button) findViewById(R.id.button2);
// set onclick listeners for buttons
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Context context = null;
switch (v.getId()) {
case R.id.button1:
Intent intent1 = new Intent(context, WebActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(context, YouTubeActivity.class);
startActivity(intent2);
break;
}
}
// Initiating Menu XML file (menu.xml)
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.webView:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"treavor.brown5875#gmail.com"});
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
return false;
}
}
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/visit_our_site" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/youtube" />
</LinearLayout>
uhhh. you have Context context = null in the button click.... clearly that is the problem
I think you error come from line 39
Context context = null;
You should erase this line and
Instanciate your intent with
Intent intent1 = new Intent(MainActivity.this, WebActivity.class);
startActivity(intent1);
You should the same for intent 2

Open browser to web page Android App

Trying to grasp Java and Android would like help with a simple task of opening a users browser after they click a button.
I have been doing tutorials for the last two days though it might help if I just took a stab at it and got feedback. thanks in advance for any help.
main.xml:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bgimage2">
>
<Button
android:id="#+id/goButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="#string/start"
android:layout_x="80px"
android:layout_y="21px"
>
</AbsoluteLayout>
GetURL.java:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.view.View.OnClickListener;
String url = "http://www.yahoo.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
i.setData(u);
public class patriosar extends Activity {
private Button goButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast toast = Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
}
}
It's close, but a few things are in the wrong place or missing. The below code works -- I tried to make the minimum necessary alterations. You could load both versions into something like WinMerge to see exactly what changed.
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bgimage2"
>
<Button
android:id="#+id/goButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="#string/start"
android:layout_x="80px"
android:layout_y="21px"
></Button>
</LinearLayout>
GetURL.java:
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class GetURL extends Activity {
private Button goButton;
String url = "http://www.yahoo.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goButton = (Button)findViewById(R.id.goButton);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
}
}
(You also need a bgimage2.png file in /res/drawable/ and a start string in /res/values/strings.xml, of course).
To simplify you could do
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.yahoo.com"));
startActivity(intent);

Categories

Resources