Android App crashing at beginning - java

I'm learning Android development and I'm wondering why is my app crashing
Main code:
package com.tester.myapp;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
public class Main extends Activity {
Button carrega;
TextView texto;
#Override
protected void onCreate(Bundle savedInstanceState) {
carrega = (Button)findViewById(R.id.carregar);
texto = (TextView)findViewById(R.id.textView3);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
carrega.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
texto.setText("newtext");
}
});
}
#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;
}
}
And my XML is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="35dp"
android:background="#A5BB76"
android:text="#string/message" />
<Button
android:id="#+id/carregar"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="#string/OK"
/>
</LinearLayout>
And this app works OK just by the XML, but if I define those variables (Button and TextView) it crashes at start. Why is this happening? How can I solve this? If I take off my Java new code (and maintain the default) the app works, but it doesn't whenever I declare one of those variables.
I appreciate your time. Thank you very much. Any help would be great.

You should Initialise the View after the setContentView(R.layout.activity_main);
Change It
#Override
protected void onCreate(Bundle savedInstanceState) {
carrega = (Button)findViewById(R.id.carregar);
texto = (TextView)findViewById(R.id.textView3);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
To
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
carrega = (Button)findViewById(R.id.carregar);
texto = (TextView)findViewById(R.id.textView3);

Related

Its is showing that cannot find symbol can any one fix it?

Ive tried copying the instance of main class to sub class but it says cant find symbol
Below are the code ive tried
Here is my HTML CODE
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#drawable/shiva" >
<Button
android:id="#+id/bp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="509dp"
android:layout_marginBottom="91dp"
android:text="#string/play" />
<Button
android:id="#+id/bp1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="94dp"
android:layout_marginTop="94dp"
android:layout_marginEnd="410dp"
android:layout_marginBottom="91dp"
android:text="#string/pause" />
<Button
android:id="#+id/bp2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="95dp"
android:layout_marginTop="95dp"
android:layout_marginEnd="308dp"
android:layout_marginBottom="93dp"
android:text="#string/stop" />
</android.widget.RelativeLayout>
Here is my java code
package com.example.rd;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button Play;
Button Pause;
Button Stop;
MediaPlayer md;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Play = findViewById(R.id.bp);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
md = MediaPlayer.create(getApplicationContext(), R.raw.rudhra);
md.start();
}
MediaPlayer md;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Pause = findViewById(R.id.bp1);
Pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
md = MediaPlayer.create(getApplicationContext(), R.raw.rudhra);
md.pause();
}
MediaPlayer md;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState);
setContentView(R.layout.activity_main);
Stop = findViewById(R.id.bp2);
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
md = MediaPlayer.create(getApplicationContext(), R.raw.rudhra);
md.stop();
}
});
};
});
}
});
}
Here im getting 2 errors
1.cannot find symbol
super.onCreate(savedInstanceState);
2.cannot find symbol
super.onCreate(savedInstanceState);
As im beginner can any1 help me to fix it
Learn about Activity Lifecycle first. According to it an activity has only one oncreat() method in its lifecycle. Here you seem to have added two oncreate().
Remove the second one and your code will work.

Using seterror for edittext validation in android

I am trying to validate a edittext using the seterror method.I am using the focus changed listener for checking whether the edittext has length of zero or not.But when i try to type into the required edittext, i cannot type into it and the text is being typed into the second one.Please help!!
The code:
package com.example.usernamevalidation;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText txtusername,txtpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtusername=(EditText) findViewById(R.id.txtusername);
txtpassword=(EditText) findViewById(R.id.txtpassword);
txtusername.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
if(txtusername.getText().toString().length()==0)
{
txtusername.requestFocus();
txtusername.setError("Username cannot be left blank");
}
}
}
});
}
#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;
}
}
The xml:
<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="wrap_content"
android:orientation="vertical"
>
<EditText
android:layout_width="300px"
android:layout_height="wrap_content"
android:id="#+id/txtusername"
/>
<EditText
android:layout_width="300px"
android:layout_height="wrap_content"
android:id="#+id/txtpassword"
/>
</LinearLayout>
Remove this line : txtusername.requestFocus();
Use a TextWatcher and in its onTextChanged() check whatever you want.
it is very simple you have create more your code more complex let try this code Use TextUtils TextUtils.isEmpty-Returns true if the string is null or 0-length.
EditText txtusername = (EditText) findViewById(R.id.txtusername);
EditText txtpassword = (EditText) findViewById(R.id.txtpassword);
if(TextUtils.isEmpty(txtusername.getText().toString())){
txtusername.setError("Username cannot be left blank");
txtusername.requestFocus();
}
if(TextUtils.isEmpty(txtpassword.getText().toString())){
txtpassword.setError("password cannot be left blank");
txtpassword.requestFocus();
}
//do logging process

onClick button not working in a basic android project

I have just started programming in Android and I couldn't get the result on clicking button that I expected. Here s the code.
.java file
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class AndroidLove extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_love);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_love, menu);
return true;
}
public void onButtonClicked(View view) {
TextView textView=(TextView)findViewById(R.id.textView1);
textView.setVisibility(View.VISIBLE);
}
}
.xml file
<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=".AndroidLove" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="104dp"
android:text="#string/hello_world"
android:visibility="invisible" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:text="#string/Button"
android:onClick="onButtonClicked" />
strings.xml file
<resources>
<string name="app_name">AndroidLove</string>
<string name="action_settings">Settings</string>
<string name="hello_world">First Line\nSecond Line\nThird Line</string>
<string name="Button">Get Lyrics</string>
On clicking the button, the following text should be displayed but its not displayed:-
First Line
Second Line
Third Line
Please help
Edit: Maybe and probably your binding is wrong about onclick, try below code instead of top. Put that code into your onCreate method.
Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView=(TextView)findViewById(R.id.textView1);
textView.setVisibility(View.VISIBLE);
}
});
You need to get the string value from the strings.xml file which can be acheived by
String st =getResources.getString(R.string.hello_world);
Then set that to textview by
textView.setText(st);
Try this code:
public class AndroidLove extends Activity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_love);
textView=(TextView)findViewById(R.id.textView1);
button1 = (Button)findViewByid(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
// do your stuff here
String _data =getResources.getString(R.string.hello_world);
textView.setText(_data);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

Display programming language code exactly as it is in textview

Is there any way to display the code by the help of using textview. Here is my problem, when i write the code into android:text=" " of the textview it shows an error.I am just trying to show the code using textview.
Please help me
Error 1(Line 14):String literal is not properly closed by a double-quote
Error 2(line 20):Multiple markers at this line
- Illegal modifier for the local class MainActivity; only abstract or final is
permitted
- The nested type MainActivity cannot hide an enclosing type
Here is my xmlcode:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</FrameLayout>
Here is my Java Code:
package com.example.test;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.TextView;
import com.example.han.R;
public class MainActivity extends ActionBarActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView1);
tv.setText("package com.example.test;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import com.example.han.R;
public class MainActivity extends ActionBarActivity {
#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;
}
}");
}
}

App crashes when i try to set onClickListener

I need help on solving an issue with app crashing when i try to set onClickListener on a button (btOK).
This is my MainActivity.java:
package edu.np.ece.mapg.newsweather;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import edu.np.ece.mapg.proj.fragments.TabsPagerAdapter;
import edu.np.ece.mapg.proj.rss.RssItem;
import edu.np.ece.mapg.proj.rss.RssReader;
public class MainActivity extends FragmentActivity {
ViewPager mViewPager;
TabsPagerAdapter mAdapter;
ActionBar mActionBar;
String[] tabStrings = {"Main", "News", "Weather"};
TextView tv;
Button btOK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btOK = (Button)findViewById(R.id.btOK);
tv = (TextView)findViewById(R.id.textView1);
btOK.setOnClickListener(asd);
//Initialize
mViewPager = (ViewPager)findViewById(R.id.pager);
mActionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); //Initialize the created adapter class
mViewPager.setAdapter(mAdapter);
mActionBar.setHomeButtonEnabled(false);
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add tabs
for(String tab_name : tabStrings){
mActionBar.addTab(mActionBar.newTab().setText(tab_name).setTabListener(tabListener));
}
mViewPager.setOnPageChangeListener(pageListener);
// MINI PROJ PHASE 2 //
try{
RssReader rssReader = new RssReader("http://news.google.com/news?pz=1&cf=all&ned=en_sg&hl=en&output=rss");
ListView newsListView = (ListView)findViewById(R.id.newsListView);
//Create list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(getBaseContext(), android.R.layout.simple_list_item_1, rssReader.getItems());
//Set list adapter for listview
newsListView.setAdapter(adapter);
//Set listview item click listener
newsListView.setOnItemClickListener((OnItemClickListener) new ListListener(rssReader.getItems(), this));
adapter.notifyDataSetChanged();
}
catch(Exception e){
Log.e("SimpleRssReader", e.getMessage());
}
}
View.OnClickListener asd = new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText("OK");
}
};
ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// On changing page, make respected tab selected
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {};
#Override
public void onPageScrollStateChanged(int arg0) {};
};
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
#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;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
news_fragment.xml , the place where i set my buttons:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/btOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="#+id/newsListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
You have
setContentView(R.layout.activity_main);
activity_main.xml does not a have a button with id btOK
Your news_fragment.xml has a button.
So if you initialize button in Activity you get NullPointerException leading to crash.
Its the same for TextView and ListView.
findViewById will look for a view with the id in the current inflated layout.
http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
Change
View.OnClickListener asd = new View.OnClickListener()
to
btOK.OnClickListener(new View.OnClickListener())
Similarly
SetOnPageListener to mViewPager and TabListener to mActionBar
buttonOk and textView1 are in news_fragment.xml, You can fetch these views in fragment where you setting news_fragment.xml ,

Categories