Code Error Java?
public class Main {
public static void main(String[] args) {


    GUI gui = new GUI();
    
    }
    
   public static int fak (int n) {
        if (n == 0) {
            return 1;
        }
        return n * fak(n - 1);
    }
    
}

import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class GUI extends JFrame {
    JButton button = new JButton("Berechnen");
    JLabel label = new JLabel("Bitte geben Sie die Zahl ein: ");
    JTextField textfield = new JTextField(2);
    JOptionPane popup = new JOptionPane();
    JPanel panel = new JPanel();
    
    public GUI () {
        setSize(300, 300);
        setTitle("Fakultätsrechner");
        setLayout(new FlowLayout());
        setVisible(true);
        
        panel.add(textfield);
        panel.add(label);
        panel.add(button);
        add(panel);
        
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);


        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String input = textfield.getText();
                    int number = Integer.parseInt(input);
                    int result = Main.fak(number);
                    JOptionPane.showMessageDialog(null, "Die Fakultät von " + number + " ist " + result);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "Bitte geben Sie eine gültige Ganzzahl ein.");
                }
            }
        });
        
    }





}

Error: java.lang.ClassNotFoundException: Main

Aber wieso findet er denn die Main-Klasse nicht? Verstehe ich nicht.

App, Java, Minecraft, Array, Code, Eclipse, Minecraft Server, Programmiersprache, Swing, game-development, Bukkit, Spigot, Java Swing, Android Studio
Asynchrones Laden in Jetpack Compose geht nicht?

Hallo, ich habe folgenden Code in meiner Android Jetpack Compose App, wenn ich die App starte bleibt der Bildschirm wo die Elemente der LazyColumn sein sollten jedoch leer. In der Konsole werden aber die Namen von den Filmen angezeigt (siehe println in der getTrendingMoviesAsync() Methode)

Code in der MainScreen Klasse:

val movies by remember { mutableStateOf(ArrayList<JSONObject>(emptyList())) }
val coroutineScope = rememberCoroutineScope()

LaunchedEffect(true) {
    coroutineScope.launch { 
        val result = getTrendingMoviesAsync()
        if (result != null){
            movies.addAll(result)
        }
    }
}

LazyColumn(modifier = Modifier.padding(top = 135.dp)){
    items(movies){ movie ->
        Text(text = movie.getString("title"))
        Spacer(modifier = Modifier.height(10.dp))
    }
}

Code von der Methode:

suspend fun getTrendingMoviesAsync(): ArrayList<JSONObject>? {
    return withContext(Dispatchers.IO) {
        try {
            val movies = ArrayList<JSONObject>()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("https://api.themoviedb.org/3/trending/movie/week?language=de-DE")
                .get()
                .addHeader("accept", "application/json")
                .addHeader(
                    "Authorization",
                    "Bearer <apikey>"
                )
                .build()

            val response = client.newCall(request).execute()
            val json = JSONObject(response.body()?.string())
            val results = json.getJSONArray("results")
            for (i in 0 until results.length().coerceAtMost(30)) {
                val movie = results.getJSONObject(i)
                println(movie.getString("title"))
                movies.add(movie)
            }

            movies
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}

Kann mir jemand weiterhelfen?

App, Android, Code, Programmiersprache, asynchron, compose, jetpack, Android Studio, Kotlin
Wie kriege ich den Response der API in mein TextViewField in Android Studio?

Hallo,

momentan sitze ich daran, eine Android App mit Android Studio zu entwickeln. Die App soll GET und POST benutzen können, um mit einer API arbeiten zu können.

Soweit funktioniert das auch alles. Meine Frage bezieht sich hier auf Folgendes:

Ich habe in der MainActivity den TextView TW_Rueckgabe. Hier soll der Response der POST-Funktion gespeichert werden, da ich den gerne in der App anzeigen lassen will.

Nun habe ich aber bereits ein paar Sachen ausprobiert, allerdings vergebens.

Nun zu meiner eigentlichen Frage:

Wie kriege ich hin, das der Response der POST-Klasse in dem TextView TW_Rueckgabe gespeichert wird?

Danke im Voraus.

MfG

MainActivity.java

final TextView[] TW_Rueckgabe = {
  findViewById(R.id.textViewRueckgabe)
};
Button sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(v -> {
  String POST_url = "http://dphost.ddns.net:1573/cool/post.php";
  String requestData = "data=" + TW_Benutzername.getText().toString();
  POSTRequestTask test = (POSTRequestTask) new POSTRequestTask().execute(POST_url, requestData);
  TW_Rueckgabe[0].setText(test.fetching_data);
});

POSTRequestTask.Java

class POSTRequestTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
    String url = params[0];
    String requestData = params[1];
    String response = "";

    try {
      URL obj = new URL(url);
      HttpURLConnection con = (HttpURLConnection) obj.openConnection();

      // add request header
      con.setRequestMethod("POST");
      con.setDoOutput(true);

      // add request data
      DataOutputStream wr = new DataOutputStream(con.getOutputStream());
      wr.writeBytes(requestData);
      wr.flush();
      wr.close();

      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + url);
      System.out.println("Response Code : " + responseCode);

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer responseBuffer = new StringBuffer();

      while ((inputLine = in.readLine()) != null) {
        responseBuffer.append(inputLine);
      }

      in.close();
      response = responseBuffer.toString();
    }
    catch (IOException e) {
      e.printStackTrace();
    }

    return response;
  }

  @Override
  protected void onPostExecute(String result) {
    // print result
    System.out.println("\n\n\n" + result + "\n\n\n");
    fetching_data = result;
  }

  public String returnString() {
    return fetching_data;
  }
}
Java, Android, Android App, Programmiersprache, Android Studio
jetpack compose - wie starte ich eine neue Activity?

Hallo zusammen

Ich habe folgendes Composable in meinem Code:

@Composable
fun Toolbar() {

    // Create a boolean variable
    // to store the display menu state
    var mDisplayMenu by remember { mutableStateOf(false) }

    // fetching local context
    val mContext = LocalContext.current

    // Creating a Top bar
    TopAppBar(
        title = { Text(stringResource(R.string.app_name)) },backgroundColor = Color(0xFFFFFFFF),
                actions = {

                    // would create a Toast message
                    IconButton(onClick = {
                        val intent = Intent(this, LockScreenActivity::class.java)
                        startActivity(intent)
                        Toast.makeText(mContext, "Lock app...", Toast.LENGTH_SHORT).show() }) {
                        Icon(Icons.Outlined.Lock, "")

Nun möchte ich gerne, dass wenn man auf das lock icon klickt, die dazugehörige Activity "LockScreenActivity" gestartet wird. Folgende Fehlermeldung erhalte ich jedoch bei "val intent = Intent"

None of the following functions can be called with the arguments supplied.
<init>(Context!, Class<*>!) defined in android.content.Intent
<init>(String!, Uri!) defined in android.content.Intent

Ich weiss nicht genau, warum diese Fehlermeldung auftritt bzw. warum es nun noch ein Argument benötigt. Könnte mir bitte Jemand helfen?

Eine Zeile weiter unten bestätigt sich nochmals mein Fehler mit der Meldung No value passed for parameter 'intent'

No value passed for parameter 'intent'

Vielen Dank für jede Hilfe.

programmieren, Android, Code, compose, Android Studio, Kotlin
Android App löscht Session automatisch bei onDestroy?

Ich habe eine App, wo man sich anmelden muss.

Die SessionID wird in der Login Activity empfangen und gespeichert. Wenn ich auf einer anderen Activity bin, hole ich die SessionID aus den ShaPref und hänge sie an den Header. Dann erhalte ich einen Response. Alles funktioniert einwandfrei.

Aber sobald ich die App schließe und den Login überspringe, dann wird ja die SessionID wieder aus den ShaPref geholt und an den Header gehängt.

Die SessionID ist weiterhin vorhanden! Dies prüfe ich anhand des Toast und Logs.

Aber ich erhalte den Response, dass ich ausgeloggt sei. Und die Session ist komplett leer.

Meine Vermutung ist:

Das die SessionID nur der Ort ist, wo die Datei mit den Werten gespeichert ist. Also das ich die SessionID an den Header hänge und dann weiß die Seite, welche Datei benutzt werden soll. Aber wenn man aus der App herausgeht, löscht Android automatisch diese Datei. Doch die SessionID-Adresse bleibt bestehen.

Fragen:

  • Wie kann ich die App schließen, ohne dass Android die Datei löscht?
  • Wo wird die Session auf dem Handy gespeichert? Ich kann es ja am PC einsehen.
  • Wie kann ich verhindern, dass Androids onDestroy etc. die Datei löscht?

Und wie kann ich dafür sorgen, dass Android bei onDestroy etc. die Datei löscht?

Wenn ich angemeldet sein möchte und ich herausgehe und wieder rein, bleibt die SessionID. Aber auf der Webseite ist sie leer. Aber wenn ich nicht angemeldet sein möchte, dann wird die ShaPref gelöscht und dann soll auch die Datei gelöscht werden.

Ich hoffe, ihr habt eine Lösung, wie man die automatische Löschung von dieser Datei bei Verlassen der App verhindert.

Ich danke euch im Voraus.

App, programmieren, Java, Android, session, Speicherort, Android Studio
Android Studio: Wieso verändern die Elemente ihre Position?

Hey,

ich habe da ein kleines Problem. Auf dem PC sind alle Elemente dort, wo sie sein sollten, aber wenn ich die App auf dem Handy ausführe, sind die Elemente irgendwie bzw. irgendwo platziert. Kann mir jemand vielleicht sagen, woran es liegen könnte?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/black_shade_1"
  tools:context=".MainActivity">
  <ImageView 
    android:layout_width="152dp"
    android:layout_height="185dp" 
    app:srcCompat="@drawable/iconqrlogo" 
    android:id="@+id/imageView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="32dp"
    app:layout_constraintHorizontal_bias="0.498" />
  <ProgressBar
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:visibility="visible"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    android:layout_marginTop="56dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView" />
  <Button
    android:text="@string/generateButton"
    android:layout_width="250dp"
    android:layout_height="60dp"
    android:id="@+id/generateQrCode"
    app:backgroundTint="@color/yellow"
    android:textColor="#000000"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintHorizontal_bias="0.496"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="160dp" />
  <Button
    android:text="@string/scanCode"
    android:layout_width="250dp"
    android:layout_height="60dp"
    android:id="@+id/scanQrCode"
    app:backgroundTint="@color/yellow"
    android:textColor="#000000"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progressBar"
    android:layout_marginTop="48dp"
    app:layout_constraintHorizontal_bias="0.503"
    app:layout_constraintBottom_toTopOf="@+id/generateQrCode"
    app:layout_constraintVertical_bias="0.061" />
</androidx.constraintlayout.widget.ConstraintLayout>
Bild zu Frage
Computer, App, programmieren, Java, Android, Android App, Android Studio
Wieso ändern sich die Position der Elemente am Handy?

Hey Leute,

ich habe ein kleines Preoblem und zwar die Positionen der Elemente im Android Studio enspricht nicht der am Handy also am Handy werden sie komplett anders angeordernt und nicht wie ich sie im Android Studio positioniert hatte.

Z.B. der Button sollte oben sein und nicht unten!

Hat jemand vielleicht eine Idee voran es liegen könnte?

Danke im Voraus


  

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="158dp"
        android:layout_marginBottom="274dp"
        android:text="@string/button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>



---------------------------manifest------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Test">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


-----------------gradle-------------------------
plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.test"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
Bild zu Frage
programmieren, Design, Java, Android App, Android Studio
Android Studio App stürzt ab nach klick auf Button?

Hallo,

ich habe eine Android Studio Applikation mit einer Bottom Navigation bar, bei welcher unter dem Reiter "Profile" ein User hinzugefügt werden soll. Wenn ich dort auf "Add User" klick stürzt die App allerdings ab, in der Version ohne Navigationsbar funktioniert das allerdings einwand frei. Vielleicht kann mir jedmand helfen, den Fehler zu finden.

Hier ist die UI von Profile:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout ...
    ...
    <Button
        android:id="@+id/btAddUser"
        ...
        android:text="Add User"
        android:onClick="onAddUser"
        />

</LinearLayout>

Hier die UI der BottomBar:

<?xml version="1.0" encoding="utf-8"?>
<...
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment_container"
        >  
...
 app:menu="@menu/bottom_navigation"/>
    </FrameLayout>

Die Klasse zur BottomBar:

package com.example.bottomnav;
import ...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

BottomNavigationView bottomNavigation = findViewById(R.id.bottom_navigation);    bottomNavigation.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
...
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId())
{
case R.id.nav_projects:
selectedFragment = new ...
ProfileFragment();
break;
}
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}};}

Hier der Code zum Profil hinzufügen:

@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_profile, container, false);
}

public
class MyActivity extends AppCompatActivity {
    ...

    Button btAddUser;
...

    Boolean isAdmin = Boolean.FALSE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_profile);
       ...
        btAddUser = findViewById(R.id.btAddUser);

        btAddUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {onAddUser(btAddUser);}

    public void onAddUser(View view) {
...

Computer, Java, Android, Informatik, XML, Progamm, Android Studio

Meistgelesene Fragen zum Thema Android Studio