I'm just a beginner in android development. Recently I'm developing an app which converts a unit between other units. The code was growing very large & it became eventually cumbersome to maintain and finding, fixing bugs. So, I tried to split the MainActivity.java into other classes, but now the apps keeping crashing. Android Studio can build and run the project, but it no longer runs on my device.
MainActivity.java file contains
package com.gazzali.spinitmeow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinnerMainChoice, spinnerInputChoice, spinnerOutputChoice;
EditText getInputValueID;
double inputValue;
TextView outputValue;
Button buttonConvert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* ------------ Main code Starts Here ----------------*/
/* Main conversion Type choice with Spinner (Drop Down menu)*/
spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
// [IMPORTANT] Set Spinner Click Listener
spinnerMainChoice.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
R.array.MainChoices_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerMainChoice.setAdapter(adapterMainChoice);
/* Input Conversion type choice with Spinner */
spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
spinnerInputChoice.setOnItemSelectedListener(this);
/* Output Conversion type choice with Spinner */
spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
spinnerOutputChoice.setOnItemSelectedListener(this);
/* for input and output fields */
getInputValueID = findViewById(R.id.editTextIDInputValue);
String inputValueString = getInputValueID.getText().toString();
if(!TextUtils.isEmpty(inputValueString))
{
try
{
inputValue = Double.parseDouble(inputValueString);
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
outputValue = findViewById(R.id.textViewIDOutputValue);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. retrieve the selected item
String selectedMainChoice = parent.getItemAtPosition(pos).toString();
Log.i("Selected", selectedMainChoice);
//Toast.makeText(MainActivity.this, "Selected: " + selectedMainChoice, Toast.LENGTH_SHORT).show();
/* This is where I made the separation ; previously the contents inside the spinnerSelects's setInputOutSpinner()
was inside the MainActivity as a method */
spinnerSelects spinnerSelects = new spinnerSelects();
spinnerSelects.setInputOutputSpinners(selectedMainChoice);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
spinnerSelects.java file contanis:
package com.gazzali.spinitmeow;
import android.widget.ArrayAdapter;
public class spinnerSelects extends MainActivity{
protected void setInputOutputSpinners(String selectedMainChoice) {
switch (selectedMainChoice)
{
case "Length": {
spinnerInputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.LengthChoices_array)));
spinnerOutputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.LengthChoices_array)));
}
break;
case "Temperature": {
spinnerInputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.TemperatureChoices_array)));
spinnerOutputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.TemperatureChoices_array)));
}
break;
case "Weight": {
spinnerInputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.WeightChoices_array)));
spinnerOutputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.WeightChoices_array)));
}
break;
}
}
}
The Logcat shows this traces,which is much alien to me.
2019-07-20 19:55:12.757 18958-18958/com.gazzali.spinitmeow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gazzali.spinitmeow, PID: 18958
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:91)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
at com.gazzali.spinitmeow.spinnerSelects.setInputOutputSpinners(spinnerSelects.java:13)
at com.gazzali.spinitmeow.MainActivity.onItemSelected(MainActivity.java:83)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
at android.widget.AdapterView.access$300(AdapterView.java:53)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
2019-07-20 19:55:12.787 18958-18958/com.gazzali.spinitmeow I/Process: Sending signal. PID: 18958 SIG: 9
at com.gazzali.spinitmeow.spinnerSelects.setInputOutputSpinners(spinnerSelects.java:13)
at com.gazzali.spinitmeow.MainActivity.onItemSelected(MainActivity.java:83)
these two lines have blue underlined whereas others in red.
Can someone please tell me where I need to fixe bugs so my doesn't crashes anymore?
Thanks in Advance.
For solving your current NullPointerException problem,
pass your activity context to your spinnerSelects desired method
spinnerSelects.setInputOutputSpinners(MainActivity.this,selectedMainChoice);
and in this method use that activity to getResources
protected void setInputOutputSpinners(Activity activity, String selectedMainChoice) {
switch (selectedMainChoice)
{
case "Length": {
spinnerInputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
activity.getResources().getStringArray(R.array.LengthChoices_array)));
spinnerOutputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_dropdown_item,
activity.getResources().getStringArray(R.array.LengthChoices_array)));
}
break;
}
}
Hope it will solve your problem but in my opinion, your this code is
not good. you can improve it.
if my solution did not work, don't extend MainActivity and keep the
spinnerSelects as just a Java class and pass Spinner spinnerInputChoice variables
to the desired class methods.
Happy coding!!!
First of all you should not extend any Activity class in any other class. Instances of Activity classes would be created by Android system when you start them using an Intent. We should not create Activity instances using its constructor.
In spinnerSelects class, the spinnerInputChoice you are trying use is not part of the MainActivity's instance which was created by Android system. Because the instance of spinnerSelects you have created in onItemSelected method has different version of extended MainActivity.
Update
Check if following solve your problem:
Remove MainActivity inheritense from spinnerSelects.
In onItemSelected, supply context in spinnerSelects through constructor. You can use it to getResources.
public class spinnerSelects {
private Context context;
public spinnerSelects(Context pContext) {
context = pContext;
}
// Your code
}
Change setInputOutputSpinners method's return type to ArrayAdapter<CharSequence> and then return created ArrayAdapter<CharSequence> instance.
In onItemSelected method set the returned adapter from setInputOutputSpinners to spinner.
Related
I am trying to extract the value of some particular string values in another class converter.java class from MainActivity.java , but it's cannot be shown. No Logs are shown. Even, if I want to get Data from another class spinnerSelects.java It's also no longer shown in some places. Can You please help me?
MainActivity.java code is here:
package com.gazzali.spinitmeow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener{
Spinner spinnerMainChoice;
Spinner spinnerInputChoice;
Spinner spinnerOutputChoice;
EditText getInputValueID;
Double inputValue;
TextView outputValueTextViewFromConverter;
Button buttonConvert;
String selectedMainChoice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* ------------ Main code Starts Here ----------------*/
/* Main conversion Type choice with Spinner (Drop Down menu)*/
spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
// [IMPORTANT] Set Spinner Click Listener
spinnerMainChoice.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
R.array.MainChoices_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerMainChoice.setAdapter(adapterMainChoice);
/* Input Conversion type choice with Spinner */
spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
/* Output Conversion type choice with Spinner */
spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
/* for input and output fields */
getInputValueID = findViewById(R.id.editTextIDInputValue);
/* ---- Setting Button Properties -----*/
buttonConvert = findViewById(R.id.buttonIDConvert);
buttonConvert.setOnClickListener(this);
/* --- Setting Output TextView field ----*/
outputValueTextViewFromConverter = findViewById(R.id.textViewIDoutputValueToConverter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. retrieve the selected item
selectedMainChoice = parent.getSelectedItem().toString();
Log.i("Selected", selectedMainChoice);
/* Toast.makeText(MainActivity.this, String.valueOf(inputValue), Toast.LENGTH_SHORT).show();*/
/* Implement object of spinnerSelects class*/
spinnerSelects spinnerSelectsInMain = new spinnerSelects(this, spinnerInputChoice, spinnerOutputChoice);
/* the main EVIL '(context) this' in the 2nd parameter, 5 hours wasted, but I learnt many more */
spinnerSelectsInMain.setInputOutputSpinners(selectedMainChoice);
/* calling test for converter class */
/*testOnConverter();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void testOnConverter(){
converter converterInMain = new converter(selectedMainChoice);
}
#Override
public void onClick(View view)
{
String inputValueString = getInputValueID.getText().toString();
inputValue = Double.parseDouble(inputValueString);
/*Toast.makeText(this, String.valueOf(inputValue), Toast.LENGTH_SHORT).show();*/
converter converterInMain = new converter(selectedMainChoice);
double convertedValue = converterInMain.convert(inputValue);
outputValueTextViewFromConverter.setText(String.valueOf(convertedValue));
}
}
converter.java codes here:
package com.gazzali.spinitmeow;
import android.content.Context;
import android.util.Log;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
public class converter {
public String MainChoice, inputChoice, outputChoice;
public converter() {
}
public converter(String selectedMainChoiceFromMain) {
this.MainChoice = selectedMainChoiceFromMain;
/* No Log for Main Choice is Being Shown Here */
Log.i("Main Choice is", MainChoice);
}
public converter(String inputChoiceFromSpinnerSelects, String outputChoiceFromSpinnerSelects){
this.inputChoice = inputChoiceFromSpinnerSelects;
this.outputChoice = outputChoiceFromSpinnerSelects;
/* This Logs Shows But ONLY here */
/* IF I try to show the logs anywhere else in the class, */
/* Either null exception or No Log output */
Log.i("Sub Input Choices are:", inputChoice);
Log.i("Sub Output Choices are:", outputChoice);
}
public double convert(double inputValueForEditTextFieldFromMain)
{
double inputValueInConverter = inputValueForEditTextFieldFromMain;
double outputValueToConverterToMain= 0.00;
/* Here I can't see the Log */
/* Apps Crashes When I press Convert Button*/
Log.i("Sub Input Choices are:", inputChoice);
converterLength converterLengthInConverter = new converterLength();
outputValueToConverterToMain = inputValueInConverter * 22;
/*switch (MainChoice)
{
case "Length":
outputValueToConverterToMain = converterLengthInConverter.convertLength(inputChoice, outputChoice, inputValueInConverter);
break;
}*/
return outputValueToConverterToMain;
}
}
Apps Keeep crashing when I press the convert button.
Locat error shows :
2019-07-21 16:48:33.406 10979-10979/com.gazzali.spinitmeow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gazzali.spinitmeow, PID: 10979
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:166)
at com.gazzali.spinitmeow.converter.convert(converter.java:46)
at com.gazzali.spinitmeow.MainActivity.onClick(MainActivity.java:104)
UPDATE
here's my spinnerSelects class which passes inputChoice and outputChoice parameter to converter class, but still I am geing that weird error.
Although I set the constructor values of converter class by the parameter passed by spinnerSelects , it never sets it values as I can't see inputChoice value inside converter class
package com.gazzali.spinitmeow;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class spinnerSelects implements AdapterView.OnItemSelectedListener{
public String inputChoice, outputChoice;
public Spinner spinnerInputChoice, spinnerOutputChoice;
public ArrayAdapter<CharSequence> adapterInputChoice, adapterOutputChoice;
private Context contextInSpinnerSelects;
public Context getContextInSpinnerSelects() {
return contextInSpinnerSelects;
}
public spinnerSelects() {
/* Empty Constructor */
}
public spinnerSelects(Context contextFromMain, Spinner spinnerInputChoiceFromMain, Spinner spinnerOutputChoiceFromMain) {
this.spinnerInputChoice = spinnerInputChoiceFromMain;
this.spinnerOutputChoice = spinnerOutputChoiceFromMain;
this.contextInSpinnerSelects = contextFromMain;
}
/**
*
* #param selectedMainChoice String retrieves Main Conversion spinner's type
*/
public void setInputOutputSpinners(String selectedMainChoice) {
switch (selectedMainChoice)
{
case "Length": {
adapterInputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.LengthChoices_array, android.R.layout.simple_spinner_item);
adapterOutputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.LengthChoices_array, android.R.layout.simple_spinner_item);
setInputOutputListenerAndDropDownAndAdapter();
}
break;
case "Temperature": {
adapterInputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.TemperatureChoices_array, android.R.layout.simple_spinner_item);
adapterOutputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.TemperatureChoices_array, android.R.layout.simple_spinner_item);
setInputOutputListenerAndDropDownAndAdapter();
}
break;
case "Weight": {
adapterInputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.WeightChoices_array, android.R.layout.simple_spinner_item);
adapterOutputChoice = ArrayAdapter.createFromResource(contextInSpinnerSelects,
R.array.WeightChoices_array, android.R.layout.simple_spinner_item);
setInputOutputListenerAndDropDownAndAdapter();
}
break;
}
}
private void setInputOutputListenerAndDropDownAndAdapter() {
spinnerInputChoice.setOnItemSelectedListener(this);
spinnerOutputChoice.setOnItemSelectedListener(this);
adapterInputChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerInputChoice.setAdapter(adapterInputChoice);
adapterOutputChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOutputChoice.setAdapter(adapterOutputChoice);
}
public Spinner getSpinnerInputChoice() {
return spinnerInputChoice;
}
public Spinner getSpinnerOutputChoice() {
return spinnerOutputChoice;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
inputChoice = spinnerInputChoice.getSelectedItem().toString();
outputChoice = spinnerOutputChoice.getSelectedItem().toString();
converter converterInSpinnerSelects = new converter(inputChoice, outputChoice);
/*converterInSpinnerSelects.setInputOutputChoice(inputChoice, outputChoice);*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Your problem might be that inputChoice is never set.
You are creating a new instance of your converter-class with this code:
converter converterInMain = new converter(selectedMainChoice);
this will ONLY run this code in your converter-instance:
public converter(String selectedMainChoiceFromMain) {
this.MainChoice = selectedMainChoiceFromMain;
/* No Log for Main Choice is Being Shown Here */
Log.i("Main Choice is", MainChoice);
}
the second constructor therefore never executes public converter(String inputChoiceFromSpinnerSelects, String outputChoiceFromSpinnerSelects){ what means that you never set inputChoicenor outputChoice in your converter-instance which means that they stay null
Log.i("Sub Input Choices are:", inputChoice); therefore gets a null as inputChoice
But I don't think this is the problem here. It should still work but just output a null into your console. As I remember Log.i() works like this: Log.i(TAG, MESSAGE) so your code should look something like this:
Log.i("CONVERTER", "Sub Input Choices are: " + inputChoice);
UPDATE
Well now you are creating a new instance of convertor in (AdapterView<?> parent, View view, int position, long id) {
converter converterInSpinnerSelects = new converter(inputChoice, outputChoice);
this will NOT update the values of the convertor-instance you create in your onClick(View view)-function.
One way of solving this problem might be to simply put the Strings static:
public static String MainChoice, inputChoice, outputChoice;
But then there is no need for creating a new instance of converter every time... so simply do this then:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
converter.inputChoice = spinnerInputChoice.getSelectedItem().toString();
converter.outputChoice = spinnerOutputChoice.getSelectedItem().toString();
}
I'm trying to create an app that has different pages for topics and questions. I have created about two activites and am about to create more, like 40 activities. How can I do this without creating up to that number of activities?
Here is my MainActivity.java codes
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the text view id
mListView = (ListView) findViewById(R.id.myList);
//Adding text to the array list
String booksArray[] = new String[]{"General Questions", "Mathematics",
"Physics",
"Chemistry",
"English"};
//Initialize the array list in the adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout
.simple_list_item_1, booksArray);
mListView.setAdapter(adapter);
//Set the listener for the list view item
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//if the position of item clicked is 1, it should open
//another activity
if(position == 1 ){
conditionOfIf();
}
else{
//A short message that notify user for an error
Toast.makeText(getApplicationContext(), "Please click on the first objcet",
Toast.LENGTH_LONG)
.show();}
}
});
}
//The real code that open another activity called Topics
private void conditionOfIf(){
Intent intent = new Intent(this, Topics.class);
startActivity(intent);
}
}
Fragments is your answer. your can create 40 fragments and have only one activity for managing that fragments.
And the best thing about fragments is that you can use the same UI for multiple purpose i.e reuse-ability which might come handy as you have large number of layouts.
i think this will be a great Fragment tutorial to start with,it is easy to understand yet powerful enough to teach you the fundamentals.
use fragments.
For learning fragments go to google or youtube videos.
There are many online sources available.
I am using a simple spinner to display buy-in values in an integer-array. The error in the Gradle Build says: method getOnItemSelectedListener in class AdapterView<T> cannot be applied to given types. There are no required arguments and the reason for the error is given as: actual and formal arguments lists differ in length where T is a type-variable: T extends Adapter declared in class AdapterView. I am not sure how to resolve the error which appears on (this):
spinner.getOnItemSelectedListener(this);
I would assume that this is correct practice as I am telling the spinner that this activity is responsible for listening to the events on the spinner.
Here is my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AdapterView.OnItemSelectedListener{
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the view from home_activity.xml
setContentView(R.layout.home_activity);
// initialize spinner
spinner = (Spinner) findViewById(R.id.buyInSpinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.buy_in, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.getOnItemSelectedListener(this);
} // end onCreate method
#Override
public void onItemSelected(AdapterView<?> adapterView, View v, int i, long l)
{
TextView myText = (TextView) v;
Toast.makeText(this, "You Selected "+myText.getText(), Toast.LENGTH_SHORT).show();
} // end onItemSelected method
#Override
public void onNothingSelected(AdapterView<?> adapterView)
{
Toast.makeText(this, "You Must Buy-In To Play", Toast.LENGTH_SHORT).show();
} // end onNothingSelected method
} // end HomeActivity class
Why do you want to get without a variable?
I think in this case you should use spinner.setOnItemSelectedListener(this); instead
I'm new to android and have have an assignment to create an email application. So I have 2 layouts and 2 activities, one for reading the email and one for writing the email. I'm trying to retain the information sent in the fields in the email writing activity for when the email is being read. The problem is at the **bolded line below - "The method setText string is undefined for the type view", and I need to get all the text view to contain the information send from the other activity. I can post the other files if its needed, all help appreciated. I have tried other ways to assign the variable to text view but can't seem to get it to work.
DisplayMessageActivity.java
package com.example.project;
import com.example.project.R.layout;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Show the Up button in the action bar.
setupActionBar();
// Get the messages from the intent
Intent intent = getIntent();
String messageto2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String messagefrom2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE2);
String messagecc2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE3);
String messagebcc2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE4);
String messagesubject2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE5);
String messagebody2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE6);
**TextView msgto = (TextView)findViewById(R.id.to2).setText(messageto2);**
TextView msgfrom = (TextView)findViewById(R.id.from2);
TextView msgcc = (TextView)findViewById(R.id.cc2);
TextView msgbcc = (TextView)findViewById(R.id.bcc2);
TextView msgsubject = (TextView)findViewById(R.id.subject2);
TextView msgbody = (TextView)findViewById(R.id.body2);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
TIA
Try to change this:
(TextView)findViewById(R.id.to2).setText(messageto2);
to
((TextView)findViewById(R.id.to2)).setText(messageto2);
Methods are resolved according to the static type of the reference. findViewById() is declared with a return type of View and since the class View doesn't declare a method setText(), the compiler complains. Use this
TextView msgto = (TextView)findViewById(R.id.to2);
msgto.setText(messageto2);
try this..
((TextView)findViewById(R.id.to2)).setText(messageto2);
TextView msgto = (TextView)findViewById(R.id.to2).setText(messageto2);
Need to be changed to
TextView msgto = (TextView) findViewById(R.id.to2);
msgto.setText(messageto2);
That should help.
I create private ArrayList<String> values;. values is assigned a value in the onCreate method (final ArrayList<String> values = new ArrayList<String>();). Another method onOptionsItemSelected tries to use values, but then a NullPointerException happens.
The whole class is here, sorry if my explanation was hard to understand. The exception occurs on line 55.
package org.sandholm.max.MCFriendsList;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ArrayAdapter;
public class MCFriendsListActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listactivity);
final ArrayList<String> values = new ArrayList<String>();
setListAdapter(new ArrayAdapter<String>(this, R.layout.listactivity, values));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
addUser = (Button) findViewById(R.id.button1);
addUser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
values.add("vurp0");
adapter.notifyDataSetChanged();
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Intent i = new Intent(v.getContext(), MCFriendsInfoActivity.class);
i.putExtra("uname", item);
v.getContext().startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
values.add("vurp0");
adapter.notifyDataSetChanged();
return true;
case R.id.item2:
//showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private Button addUser;
private ArrayList<String> values;
private ArrayAdapter<String> adapter;
}
Please tell me if you need more information(although I doubt it) and thanks in advance.
On line 23 values is declared as a local variable (different than your instance variable). Instead, change line 66 to private final ArrayList<String> values; and line 23 to values = new ArrayList<String>();
Java allows local variables and instance variables to have the same name. In this case, it uses the local variable for operations so you get no error in onCreate but later the variable is out of scope (and the instance variable still has not been assigned a value).
values which you are using at line no. 55 is an instance variable which you have defined its data type at line no. 66(and you are under impression of using line number 23 reference variable) which by default sets to null. So throwing NullPointerException.
You have two ArrayList values .One of them local which is in oncreate metod.Other one is class level and it never assigned a value.Set class level values.
private Button addUser;
private ArrayList values;
private ArrayAdapter adapter;
Better to say, make your ArrayList a class member. Of course, it's already a class member, instantiate it where it is declared. Replace your line number 66 with the following statement and use it as and when required through out the application.
private final ArrayList<String> values = new ArrayList<String>();
You're declaring the ArrayList twice in your application once as a class member and again as a local variable. In this situation, the local variable enjoys the higher priority than the class member.