• 4
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Can't use Class.forName() with v4.app.Fragment

I'm trying to run the below code during onResume().

SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.appname.MainActivity", Context.MODE_PRIVATE);
String foregroundFragment = sharedPreferences.getString("foreground_fragment", "");
try {
    Fragment fragment = (Fragment) Class.forName(foregroundFragment);
    } catch (ClassNotFoundException e) {
        Log.i("EXCEPTION!", e.toString());
    }

However, Class.forName() appears to be the wrong method since it gives the following error message:

"Inconvertible types; cannot cast 'java.lang.Class>' to 'android.support.v4.app.Fragment.'

I'm not aware of another method that allows me to retrieve a String and use it to initialise a Fragment variable. I've searched online, but haven't been able to find anything other than Class.forName(). The string I'm retrieving via SharedPreferences does contain the fragment's full name, ie. "com.example.appname.ForegroundFragment".

Is there another method I should be using? Am I going about this all wrong?

      • 2
    • If you call newInstance then it's no more the same object .. it's a new instance not the same . Now it's look like you only want to know which fragment was previously added ...
      • 2
    • Class type and Fragment are not in relation .. Thats why Inconvertible types . Also i am just wondering what exactly you trying to do with this code ?
    • @ADM I'm using it to store a reference to the visible fragment when the user switches themes. I was using ViewModel, but it's dumping its content when recreating the activity.