Android Problem mit Rückgabewert

bandchef

Mitglied
Hi Leute!

Ich programmiere hier eine kleine Übung zu einem AsyncTask. Nun ist es so, dass ich über ein Textfeld eine int-Variable laden will, die mir dann die Obergrenze einer for-Schleife bilden soll. Mein Code sieht so aus:

Code:
package com.example.asynctask;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class MainActivity extends Activity
{
	public ProgressBar progressbar1;
	public Button button1;
	private EditText edittext1;
	
	//Die Activity wird erzeugt
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//Deklarationen
		progressbar1 = (ProgressBar) findViewById(R.id.progressBar1);
		button1 = (Button) findViewById(R.id.button1);
	}
	
	//Die Activity ist sichtbar
	@Override
	protected void onStart()
	{
		super.onStart();
	}
	
	//Die Activity ist sichtbar
	@Override
	protected void onResume()
	{
		super.onResume();
	}
	
	public void startAction(View button1)
	{
		new MyAsyncTask().execute();
	}
	
	@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;
	}
	
	private class MyAsyncTask extends AsyncTask <Void, Void, Void>
	{
		@Override
		protected void onPreExecute()
		{
			button1.setEnabled(false);
			progressbar1.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void...params)
		{	
			int counter = Integer.valueOf(edittext1.getText().toString());
			
			for(int i=0; i<counter; i++)
			{
				Log.d("Test: ", String.valueOf(i));
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result)
		{
			button1.setEnabled(true);
			progressbar1.setVisibility(View.INVISIBLE);
		}
	}
	
	//Die Activity ist nicht mehr sichtbar
	@Override
	protected void onStop()
	{
		super.onStop();
	}
	
	//Die Activity wird zerstört
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
}

Die for-Schleife findet ihr sicherlich und darüber ist meine Cast vom String des Textfeldes zum int. Wenn ich nun diese App ausführe, bekomme ich die Fehlermeldung, dass es eine NullpointerException gab.
Wenn ich die Zeile mit dem Cast auskommentiere und die Obergrenze der for-Schleife hart codiere, dann läuft der Code aber. Auch beim Debuggen fällt mir der Code beim Cast aus.

Was ist daran falsch? Der Sytax-Checker sagt aber, das alles korrekt ist!

Kann mir jemand helfen?
 
Zuletzt bearbeitet:

bandchef

Mitglied
Danke für die Info. Als du geschrieben hast, ist mir der Fehler mit dem fehlenden
Code:
edittext1 = (EditText) findViewById(R.id.editText1);
ins Auge gestochen!

Danke!
 

bandchef

Mitglied
Jetzt hab ich zu dieser Aufgabe noch eine weitere Frage:

Ich soll als weiteren Schritt eine ListView implementieren, die einen Toast anzeigt, wenn man auf ein Item in der Liste klickt. Dazu hab ich eine MainListActivity.java erstellt und die dazugehörige .xml Datei.

Nun ist es so, dass die ListView nicht angezeigt wird, wenn ich das Programm im Emulator laufen lasse. Ich denke, es ist wieder das Beste, wenn ich den Code hier rein kopiere.

Android Manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.asynctask"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.asynctask.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.asynctask.MainListActivity"
            android:label="@string/title_activity_main_list" >
        </activity>
    </application>

</manifest>


MainListActivity.java
Code:
package com.example.asynctask;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainListActivity extends ListActivity
{
	public ListView listview1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main_list);
		
		String[] fakultaeten = new String[]
				{
					"Allgemeinwissenschaften/Mikrosystemtechnik",
					"Architektur","Bauingenieurwesen",
					"Betriebswirtschaft",
					"Elektro- und Informationstechnik",
					"Informatik und Mathematik","Maschinenbau",
					"Sozialwissenschaften"
				};
		listview1 = (ListView) findViewById(R.id.listView1);
		setListAdapter(new ArrayAdapter <String>(this, android.R.layout.simple_list_item_1, fakultaeten)); 		
	}
	
	protected void onListItemClick(ListView listview1, View v, int position, long id)
	{
		String selection = listview1.getItemAtPosition(position).toString();
		Toast.makeText(this, selection, Toast.LENGTH_SHORT).show();
	}

	@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_list, menu);
		return true;
	}
}


activity_main.xml:
Code:
<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:gravity="center"
    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=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:onClick="startAction"
        android:text="Start!" />

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/textView1"
        android:visibility="invisible" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1" >

    </ListView>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="number" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="Hallo User!" />

</RelativeLayout>


activity_main_list.xml
Code:
<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=".MainActivity" >



</RelativeLayout>


Was ist hier nun der Fehler, warum nichts angezeigt wird? Am manifest wird's wohl eher nicht liegen, weil die neue activity geschrieben wurde. Ich denke eher, dass es was mit den xml-Dateien auf sich hat...
 
Zuletzt bearbeitet:

dzim

Top Contributor
Ich glaube hier ist das Problem, dass du in dem RelativeLayout doch noch eine untere Grenze setzen solltest. Also noch ein android:layout_above dran - dein Layout ist mir gerade zu unübersichtlich um die richtige ID zu finden :)
 

kurztipp

Aktives Mitglied
Hallo,

deine activity_main_list.xml ist nutzlos, wenn du in
Code:
setListAdapter(new ArrayAdapter <String>(this, android.R.layout.simple_list_item_1, fakultaeten));
das simple_list_item_1, das Dir Android liefert nutzt.

Wenn Du das Layout nutzen willst, solltest Du allerdings in deiner activity_main.xml folgende ListView definieren:
[XML]<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView> [/XML]

Der Adapter nutzt nämlich diese id. Statt
Code:
findViewById(R.id.listView1);
kannst du dann nämlich auch
Code:
getListView()
nutzen, was IMHO komfortabler (und sicherer in Bezug auf das Finden der richtien View?) ist.

Möchtest Du ein eigenes Layout definieren, was Dein leeres RelativeLayout nahelegt, musst Du einen ArrayAdapter nutzen, dem Du die ID des Views mitgibst, an das die Daten gebunden werden sollen. Sonst wird die ID des Standardlayouts genommen, die ich gerade nicht weiß.

Siehe auf: Android ListView - Tutorial

Gruß
 

dzim

Top Contributor
Ach siehste... Das hab ich gar nicht gesehen... ;-)

#edit:

getListView geht nur, wenn du die android-ID für die Liste im Layout verwendest:

[XML]
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:cacheColorHint="#00000000"
android:choiceMode="singleChoice"
android:fadeScrollbars="false"
android:fastScrollEnabled="true"
android:scrollbarAlwaysDrawVerticalTrack="true" />
[/XML]

so sieht es in meinem (Linear)Layout aus... und dann klappt's auch mit dem getListView().
 
Zuletzt bearbeitet:

bandchef

Mitglied
Ich hab nun in meiner activity_main.xml unterm Punkt ListView die Zeile so abgeändert:
Code:
android:id="@android:id/list"

Nun ist es aber so, dass ich in MainListActivity.java in der Zeile
Code:
listview1 = (ListView) findViewById(R.id.listView1);
einen Fehler bekomme. Dieser sagt: "listView1 can not be resolved or is not a type"

Was iist da jetzt falsch? Ich möchte übrigens das Android-Standard-Layout nutzen. Oder bezieht sich das Standard-Layout dann auch auf die Position in meiner activity_main.xml?

Hallo,

deine activity_main_list.xml ist nutzlos, wenn du in
Code:
setListAdapter(new ArrayAdapter <String>(this, android.R.layout.simple_list_item_1, fakultaeten));
das simple_list_item_1, das Dir Android liefert nutzt.

Wenn Du das Layout nutzen willst, solltest Du allerdings in deiner activity_main.xml folgende ListView definieren:
[XML]<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView> [/XML]

Der Adapter nutzt nämlich diese id. Statt
Code:
findViewById(R.id.listView1);
kannst du dann nämlich auch
Code:
getListView()
nutzen, was IMHO komfortabler (und sicherer in Bezug auf das Finden der richtien View?) ist.

Möchtest Du ein eigenes Layout definieren, was Dein leeres RelativeLayout nahelegt, musst Du einen ArrayAdapter nutzen, dem Du die ID des Views mitgibst, an das die Daten gebunden werden sollen. Sonst wird die ID des Standardlayouts genommen, die ich gerade nicht weiß.

Siehe auf: Android ListView - Tutorial

Gruß

Ich möchte ehrlich gesagt schon mit
Code:
listview1 = (ListView) findViewById(R.id.listView1);
setListAdapter(new ArrayAdapter <String>(this, android.R.layout.simple_list_item_1, fakultaeten));
arbeiten, da mir das hier so vorgeschlagen wird.

Was muss ich hier jetzt wie abändern? Wie gesagt, wenn ich in meiner activity_main.xml "android:id="@android:id/list" schreibe, dann funktionieren die Zeilen an Code wie ich hier grad kopiert hab, nicht.
 
Zuletzt bearbeitet:

bandchef

Mitglied
Ich hab mittlerweile auch schon das
Code:
android:layout_below="@+id/editText1" />
eingefügt In der grafischen Ansicht sehe ich die Liste ja sogar. Warum aber wird sie mir nicht im programm angezeigt?

Meine Aufgabe schlägt mir aber auch vor, die listView so zu deklarieren:
Code:
<ListView
        android:id="@+id/listView1"
... />

Was muss ich denn nun am Code in der MainActivity.java ändern, dass mir die ListView angzeigt wird? Ich hab übrigens grad auch schon die activity_main_list.xml gelöscht, da ich definitiv das standardlayout von android nutzen will
 
Zuletzt bearbeitet:

dzim

Top Contributor
Stand doch alles schon oben in unseren Texten:
[XML]android:id="@android:id/list"[/XML]
Das ist deine ID.
Streiche die Zeile
Java:
listview1 = (ListView) findViewById(R.id.listView1);
komplett (!!!) aus deinem Code - unnötig!
An den Stellen im Code, an denen du nun Zugriff auf die Liste brauchst, verwendest du nun in deiner ListActivity (oder ListFragment, je nachdem) einfach [c]getListView()[/c]. Fertig.

#edit: Wenn deine Aufgabe vorschlägt, heist das nicht, dass du dem blind folgen musst. In den meisten Tutorials über Listen, in denen eine ListAcitivity oder ein ListFragment verwendet wird, wirst du das so finden. Und glaube mir: Es geht damit hervorragend, weil nur so kann
Code:
getListView()
überhaupt aufgelöst werden. Der Rest ist dann, wenn du nicht vollig abgedrehte Anforderungen an die Liste hast, eher "Piece of Cake"...
 
Zuletzt bearbeitet:

bandchef

Mitglied
Danke! Jetzt hab ich das Problem gelöst! Ein weiterer Fehler war auch noch, dass der intent zum Umschalten der activity gefehlt hat.

Jetzt läuft aber alles!
 

kurztipp

Aktives Mitglied
Hallo,

Ich hab nun in meiner activity_main.xml unterm Punkt ListView die Zeile so abgeändert:
Code:
android:id="@android:id/list"

Nun ist es aber so, dass ich in MainListActivity.java in der Zeile
Code:
listview1 = (ListView) findViewById(R.id.listView1);
einen Fehler bekomme. Dieser sagt: "listView1 can not be resolved or is not a type"

Was iist da jetzt falsch?
Der Vollständigkeit halber:

Wenn Du die ID änderst, ist klar, dass
Code:
findViewById(R.id.listView1)
nichts findet. Dabei ist es egal, ob Du die ID in
Code:
@android:id/list
oder
Code:
@+id/foobar
änderst. Die ID ist jetzt nicht mehr
Code:
listView1
und kann daher logischerweise nicht mehr gefunden werden*.
Um
Code:
findViewById();
mit der neuen ID zu benutzen, musst Du das natürlich anpassen:
Code:
findViewById(android.R.id.list);
**. Würde ich zwar nicht empfehlen, weil getListView() komfortabler ist, ist aber wie gesagt ja nur der Vollständigkeit halber.

Wenn Du in:
Java:
public void foo() {
  String foo = "bar";
  System.out.println(foo);
}
foo in bar umbenennst, erwartest Du doch auch nicht, dass:
Java:
public void foo() {
  String bar = "bar";
  System.out.println(foo);
}
noch funktioniert oder?

Code:
android.R
deshalb, weil Deine App ihre eigene Klasse R hat und
Code:
@android
auf (in
Code:
android.R
) vordefinierte Konstanten zurückgreift. Wenn Du nur
Code:
R.id.list
schreiben würdest, würde wahrscheinlich wieder eine Fehlermeldung kommen, weil Du nirgendwo
Code:
@+id/list
definiert hast

Gruß
 
Zuletzt bearbeitet:
Ähnliche Java Themen
  Titel Forum Antworten Datum
W Prüfen, ob App auf Gerät installiert ist Problem S10 Android & Cross-Platform Mobile Apps 11
W In App Purchase Problem? Android & Cross-Platform Mobile Apps 36
W Problem mit Android Studio Android & Cross-Platform Mobile Apps 0
T Android R.string.test+i Problem Android & Cross-Platform Mobile Apps 2
K Android to Pi | Websocket Problem Android & Cross-Platform Mobile Apps 3
N Intent und finish() Problem Android & Cross-Platform Mobile Apps 5
B Android App Programmierung Einsteiger Problem Android & Cross-Platform Mobile Apps 4
emeraldo Android Problem mit Bottomnavmenu Android & Cross-Platform Mobile Apps 10
I Das Problem mit der Tastatur... android:windowSoftInputMode="adjustPan" Android & Cross-Platform Mobile Apps 1
M Android App → Problem mit dem Speichern von einem Bitmap–Objekt. Android & Cross-Platform Mobile Apps 1
A Android Android Studio Emulator Problem Android & Cross-Platform Mobile Apps 1
S Android Studio Bluetooth App Problem Android & Cross-Platform Mobile Apps 6
J TicTacToe Problem bei kontrolle Android & Cross-Platform Mobile Apps 7
J Button array ID Problem Android & Cross-Platform Mobile Apps 2
M Problem bei Werteübergabe, MSQL verbindung Android & Cross-Platform Mobile Apps 3
S Android Problem mit Android Virtual Device erstellung. Android & Cross-Platform Mobile Apps 2
Anfänger2011 Text to Speech Problem Android & Cross-Platform Mobile Apps 1
S Android Android java onclick listener Problem Android & Cross-Platform Mobile Apps 9
A Android Problem mit ListView und OnItemClickListener.. Android & Cross-Platform Mobile Apps 10
K Problem mit arraylist und button Android & Cross-Platform Mobile Apps 16
R W-Lan Problem über Sockets Android & Cross-Platform Mobile Apps 1
P ViewPager Problem Android & Cross-Platform Mobile Apps 1
A Android Problem mit Video von Youtube abspielen Android & Cross-Platform Mobile Apps 4
A Android Problem mit Zurücktaste und ausgabe der Aktuellen Seite Android & Cross-Platform Mobile Apps 6
B Android Problem mit Soundwiedergabe Android & Cross-Platform Mobile Apps 2
T Android Android Sensor: Java Problem Android & Cross-Platform Mobile Apps 1
G Problem beim Rendern von 3D-Objekt Android & Cross-Platform Mobile Apps 0
L Android Gyroscope Sensor Problem Android & Cross-Platform Mobile Apps 2
S Android GPS Problem Android & Cross-Platform Mobile Apps 24
J Eclipse Emulator Problem Android & Cross-Platform Mobile Apps 1
J Eclipse Emulator Problem Android & Cross-Platform Mobile Apps 0
L Android komisches Bitmap-Größe-Problem Android & Cross-Platform Mobile Apps 8
D Android Layout Problem Android & Cross-Platform Mobile Apps 2
R Problem mit View in ScrollView Android & Cross-Platform Mobile Apps 6
R Eclipse + AndroidSDK - Problem mit Referenzen Android & Cross-Platform Mobile Apps 6
M Problem mit setOnClickListener Android & Cross-Platform Mobile Apps 4
DaniSahne96 Problem beim Appdebuggen auf Smartphone Android & Cross-Platform Mobile Apps 3
P Android Problem beim Widget - Denkfehler ? Android & Cross-Platform Mobile Apps 2
M GCM IntentService Problem Android & Cross-Platform Mobile Apps 3
D Android Gallery Problem Android & Cross-Platform Mobile Apps 5
P Problem mit Cell id Android & Cross-Platform Mobile Apps 6
L Android Problem mit "spinner" Android & Cross-Platform Mobile Apps 10
D Android problem mit geschwindigkeitsberechnung app Android & Cross-Platform Mobile Apps 2
E Android Problem mit Contact Provider Android & Cross-Platform Mobile Apps 1
H Android Problem mit ListActivity Android & Cross-Platform Mobile Apps 3
S Android Layout Problem mit fill_parent Android & Cross-Platform Mobile Apps 5
F Android ExpandableList, SimpleCursorTreeAdapter, Cursor Problem Android & Cross-Platform Mobile Apps 2
A Android Problem mit Long.getLong() bzw. Integer.getInteger() Android & Cross-Platform Mobile Apps 2
A Problem mit HTTP- Verbindung Android & Cross-Platform Mobile Apps 4
V [Java] und [JavaME] ClientServer StreamConnection . Problem beim lesen / schreiben Android & Cross-Platform Mobile Apps 2
F Eclipse JAD File erzeugen -- Problem Android & Cross-Platform Mobile Apps 10
R Ein Problem beim ausführen von folgendem Quelltext Android & Cross-Platform Mobile Apps 11
M Problem mit dem Auslesen von System Properties Android & Cross-Platform Mobile Apps 7
P wtk problem Android & Cross-Platform Mobile Apps 3
G Math exp() Problem Android & Cross-Platform Mobile Apps 4
G S40 Problem Android & Cross-Platform Mobile Apps 8
A Problem beim Subtrahieren eines Double von einem Double Android & Cross-Platform Mobile Apps 5
C Problem Device/Emulator wird nicht erkannt Android & Cross-Platform Mobile Apps 3
S Image Problem Android & Cross-Platform Mobile Apps 11
M Problem mit den Softkeys Android & Cross-Platform Mobile Apps 4
G J2ME jar-problem Android & Cross-Platform Mobile Apps 10
S Komisches Problem Android & Cross-Platform Mobile Apps 3
F Problem beim Erstellen der Jar File Android & Cross-Platform Mobile Apps 4
A Problem: Canvas-Grösse Motorola RAZR v3r Android & Cross-Platform Mobile Apps 8
S Problem mit Einbindung einer externer Bibliothek Android & Cross-Platform Mobile Apps 2
G Random - Problem Android & Cross-Platform Mobile Apps 5
E problem mit den resourcen Android & Cross-Platform Mobile Apps 2
O Problem mit Datagramconnection Android & Cross-Platform Mobile Apps 2
P Problem mit der Uhrzeit Android & Cross-Platform Mobile Apps 2
S Problem auf dem Handy Android & Cross-Platform Mobile Apps 3

Ähnliche Java Themen

Neue Themen


Oben