Alright so before you go and start stating, go look around as your title matches many questions asked here. And in that case, you're correct, but... Every single thing I've tried on these asked questions didn't help me at all.
So I'm actually trying to build an RssFeed application for Android devices (Still Learning).
My problem comes in the MainActivity, mind you. All my classes, xmls, and other content are properly coded with no issues or errors. People are saying that you should get rid of the imports that contain "android.r" and I've looked throught and haven't found any imports that contain the said quotation.
My MainActivity code:
package com.ascendapps.licknriff;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ascendapps.licknriff.R;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
RssReader rssReader = new RssReader("http://www.licknriff.com/feed/");
ListView Items = (ListView)findViewById(R.id.listView1);
// create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this.android.R.layout.simple_list_item_1, RssReader.getItems());
// --
Items.setAdapter(adapter);
// --
Items.setOnItemClickListener(new ListListener(RssReader.getItems(), this)); }catch (Exception e){
Log.e("SimpleRssReader", e.getMessage());
}
}
}
Replace
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this.android.R.layout.simple_list_item_1, RssReader.getItems());
with
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this, android.R.layout.simple_list_item_1, RssReader.getItems());
android is the namespace of the Android R class. It doesn't belong to your activity class.
The first parameter is of Context type, so you activity is a suitable parameter as it inherits from Context.
Change this:
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this.android.R.layout.simple_list_item_1, RssReader.getItems());
to this:
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this, android.R.layout.simple_list_item_1, RssReader.getItems());
this should be passed as context in constructor of ArrayAdapter class.
You have a full-stop, but you need a comma, after this here -
// ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(
// this.android.R.layout.simple_list_item_1, RssReader.getItems());
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(
this, android.R.layout.simple_list_item_1, RssReader.getItems());
I think you have typo error. While writing code, you simply type . ( dot ) instead of ',' ( comma ). Just replace . with , after this like below,
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this, android.R.layout.simple_list_item_1, RssReader.getItems());
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to make an array list, but the add method is not working.
package com.zaination.listview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ListView VarListView = (ListView) findViewById(R.id.ListView);
ArrayList<String> VarArrayList = new ArrayList<String>();
VarArrayList.add("Zain");
VarArrayList.add("Sarmad");
VarArrayList.add("Aanish");
VarArrayList.add("Haider");
}
If you would put that code into onCreate (or any other) method it would probably work.
it's need to be updated like this.
package com.zaination.listview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView VarListView = (ListView) findViewById(R.id.ListView);
ArrayList<String> VarArrayList = new ArrayList<String>();
VarArrayList.add("Zain");
VarArrayList.add("Sarmad");
VarArrayList.add("Aanish");
VarArrayList.add("Haider");
}
}
also another hint attr name VarArrayList not follow java naming convention, should start with small letter varArrayList
You wrote the code outside of any method. It has to be in any kind of method.
The easiest way is to write it directly into the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView VarListView = (ListView) findViewById(R.id.ListView);
ArrayList<String> VarArrayList = new ArrayList<String>();
VarArrayList.add("Zain");
VarArrayList.add("Sarmad");
VarArrayList.add("Aanish");
VarArrayList.add("Haider");
}
PS:
There are some small improvements (also partly recommended by Android Studio) you could do:
you can ommit the cast (ListView) because it's redundant
you can ommit the ArrayList identifier string on initialization
you should name your objects (like VarArrayList) after the lower camel case naming convention (varArrayList):
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.
I am learning Android programming from this tutorial about ArrayAdapters and ListViews.
The output does not show the string array values but instead shows: Item1, subitem1,, Item2,subitemm2...etc.
I want to know why did it happen? Do the values of string array need to be created separately or does Eclipse do that automatically? If so, where would I put/find the id mobile_list?
Here is the main activity class where string array declared:
package com.example.ListDisplay;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListDisplay extends Activity {
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS","Ubuntu","Windows7","Max OS X"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}
Please refer to this question. You need to create your own class that extends from ArrayAdapter and override getView() so you can inflate your views accordingly and getCount() so the list view knows how many items are drawn. You are not supposed to use the default implementation of the ArrayAdapter. The default implementation and the way you are using it is taking as second parameter a TextView reference and you appear to be passing a layout. Refer to the official docs for this. That's why you need to create your own class
Change
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray);
To
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray);
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 have a problem in my Android application. I have a Custom ListView Adapter, but when I launch the application the list does not show any item!
My Code :
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class AccountContents extends Activity {
private ListView ls1;
String username = fourshared.username;
String password = fourshared.password;
private AccountItem[] rootContents;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootContents = fourshared.rootContents;
CArrayAdapter adapter = new CArrayAdapter(AccountContents.this, rootContents);
setContentView(R.layout.main);
ls1 = new ListView(AccountContents.this);
ls1.setAdapter(adapter);
}
}
Does your layout contain a list view? If so, you should look that up and set the adapter on that:
ls1 = (ListView)findViewById(R.id.your_list_view_id);
Better still, make your activity a ListActivity and Android will do a lot of the work for you.
You need to add the list to your activity. To do this, add this line:
setContentView(R.layout.main);
and remove: setContentView(R.layout.main);
This will add the list into view, but remove the existing views.
or you can define a list in your xml, and, as mentioned above, find it like this:
ls1 = (ListView)findViewById(R.id.your_list_view_id);
and in xml:
<ListView android:id="#+id/ls1" ......allOtherAtributesHere...... />