简体   繁体   中英

Android - ListView disappears after setContentView()?

I have a ListView in one my activity_main.xml file, the problem is, when I click on a Item in that ListView (activity_main.xml), it calls setContentView() and loads another XML file called activity_settings.xml.

The problem is, when I click the back button in activity_settings.xml (Button to call setContentView() again and go back to activity_main.xml) The ListView from activity_main.xml disappears.

I have tried about dozen ways of fixing it, but nothing seems to work.

Here is my MainActivity.java (It is pretty big):

package com.NautGames.xectav2.app;

import {...}

public class MainActivity extends ASR {

private ToggleButton homeOnOff;
HomeHoldDown hhd = new HomeHoldDown();

int keyCode;
KeyEvent event;

Context context;

private static final String LOGTAG = "Xecta";
private static final String BOTID = "e38006d97e34053e";

private TTS myTts;
private ImageButton speakButton;
private Bot bot;
Button backB1;
Button backB2;
Button backB3;

boolean mBound = false;

SimpleAdapter simpleAdpt;

BoundService myService = new BoundService();
boolean isBound = false;

EditText name, email, mMessage, subject;

String key;
String Name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, BoundService.class);
    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

    //homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);

    name = (EditText) findViewById(R.id.etName);
    email = (EditText) findViewById(R.id.etEmail);
    mMessage = (EditText) findViewById(R.id.etAdd);
    subject = (EditText) findViewById(R.id.txtSubject);

    Button startBtn = (Button) findViewById(R.id.send);

    backB1 = (Button)findViewById(R.id.button1);
    backB2 = (Button)findViewById(R.id.button2);
    backB3 = (Button)findViewById(R.id.button3);

    //Initialize GUI elements
    setSpeakButton();

    //Initialize the speech recognizer
    createRecognizer(getApplicationContext());

    //Initialize text to speech
    myTts = TTS.getInstance(this);

    //Create bot
    bot = new Bot(this, BOTID, myTts, "assistant");

    initList();

    // We get the ListView component from the layout
    ListView lv = (ListView) findViewById(R.id.listView);


    // This is a simple adapter that accepts as parameter
    // Context
    // Data list
    // The row layout that is used during the row creation
    // The keys used to retrieve the data
    // The View id used to show the data. The key number and the view id must match
    simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});


    lv.setAdapter(simpleAdpt);

    // React to user clicks on item
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {

        public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
                                long id)
        {
            // We know the View is a TextView so we can cast it
            TextView clickedView = (TextView) view;

            //Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
            if(id == 0)
            {
                setContentView(R.layout.activity_settings);
            }

            if(id == 1)
            {
                setContentView(R.layout.activity_about);
            }

            if(id == 2)
            {
                setContentView(R.layout.activity_feedback);
            }

        }
    });
}

public void onClickSend(View v) {

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"name@email.com"});
    i.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
    i.putExtra(Intent.EXTRA_TEXT   , mMessage.getText().toString());
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

}

//from here
private ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        BoundService.MyLocalBinder binder = (BoundService.MyLocalBinder) service;
        myService = binder.getService();
        isBound = true;
    }

    public void onServiceDisconnected(ComponentName arg0) {
        isBound = false;
    }

};
//to HERE

public void showTime(View view)
{
    myService.getCurrentTime();
}


/************************************************************************
 * WHEN THE USER TURNS THE HOME LISTENING ON AND OFF
 * IT WILL START SERVICE AND STOP SERVICE
 *************************************************************************/
/*public void onToggleClicked(View view) {
    boolean on = ((ToggleButton) view).isChecked();
    if (on) {
        //Toast.makeText(MainActivity.this, "Activate Xecta with Home ON", Toast.LENGTH_LONG).show();
        //startService(new Intent(getBaseContext(), Service1.class));
    } else {
        //Toast.makeText(MainActivity.this, "Activate Xecta with Home OFF", Toast.LENGTH_LONG).show();
        //stopService(new Intent(getBaseContext(), LocalService.class));
    }
}*/

@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;
}

/*public void onClickService(View view)
{
    if(isApplicationSentToBackground(context))
    {
        hhd.onKeyLongPress(keyCode, event);
    }
}*/

/**************************************************************************
 * WHEN THE USER HOLDS DOWN THE HOME BUTTON
 *************************************************************************/
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Toast.makeText(MainActivity.this, "Key pressed long!", Toast.LENGTH_LONG).show();
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

public void onClickBack(View view)
{
    setContentView(R.layout.activity_main);

}

// The data to show
List<Map<String, String>> planetsList = new ArrayList<Map<String,String>>();

private void initList() {
    // We populate the planets

    planetsList.add(newList("page", "Settings"));
    planetsList.add(newList("page", "About"));
    planetsList.add(newList("page", "FeedBack"));

}

private HashMap<String, String> newList(String key, String name) {
    HashMap<String, String> planet = new HashMap<String, String>();
    planet.put(key, name);

    return planet;
}

public void onClick(View view)
{
    speakButton = (ImageButton) findViewById(R.id.speech_btn);

    try {
        listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),"ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
        Log.e(LOGTAG, e.getMessage());
    }
}

private void setSpeakButton() {
    speakButton = (ImageButton) findViewById(R.id.speech_btn);
    speakButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
                Log.e(LOGTAG, e.getMessage());
            }
        }
    });
}

/**
 * Provides feedback to the user when the ASR encounters an error
 */
public void processAsrError(int errorCode) {

    String errorMessage;
    switch (errorCode)
    {
        case SpeechRecognizer.ERROR_AUDIO:
            errorMessage = "Audio recording error";
            break;
        case SpeechRecognizer.ERROR_CLIENT:
            errorMessage = "Client side error";
            break;
        case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
            errorMessage = "Insufficient permissions" ;
            break;
        case SpeechRecognizer.ERROR_NETWORK:
            errorMessage = "Network related error" ;
            break;
        case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
            errorMessage = "Network operation timeout";
            break;
        case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
            errorMessage = "RecognitionServiceBusy" ;
            break;
        case SpeechRecognizer.ERROR_SERVER:
            errorMessage = "Server sends error status";
            break;
        case SpeechRecognizer.ERROR_NO_MATCH:
            errorMessage = "No matching message" ;
            break;
        case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
            errorMessage = "Input not audible";
            break;
        default:
            errorMessage = "ASR error";
            break;
    }

    try {
        myTts.speak(errorMessage,"EN");
    } catch (Exception e) {
        Log.e(LOGTAG, "English not available for TTS, default language used instead");
    }

    //If there is an error, shows feedback to the user and writes it in the log
    Log.e(LOGTAG, "Error: "+ errorMessage);
    Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}

public void processAsrReadyForSpeech() {
    Toast.makeText(this, "I'm listening", Toast.LENGTH_LONG).show();

}

public void processAsrResults(ArrayList<String> nBestList, float[] confidences) {
    String bestResult = nBestList.get(0);
    Log.d(LOGTAG, "Speech input: " + bestResult);
    // insert %20 for spaces in query
    bestResult = bestResult.replaceAll(" ", "%20");

    bot.initiateQuery(bestResult);

    //Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    myTts.shutdown();
    super.onDestroy();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    setContentView(R.layout.activity_main);
    newList(key, Name);
    initList();
}

@Override
public void onStop()
{
    super.onStop();
    Toast.makeText(MainActivity.this, "Bye bye!", Toast.LENGTH_SHORT).show();
    onKeyLongPress(keyCode, event);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

onClickBack is the button to go back to activity_main.xml, I am also initialising the ListView in onCreate().

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/onericblur"
android:orientation="vertical"
android:paddingBottom="5dp"
android:onClick="onClick"
android:weightSum="1">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:orientation="vertical" >

 <TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="#000000"
    android:paddingBottom="10dip"
    android:paddingTop="10dip"
    android:text="@string/title"
    android:textColor="#FFFFFF"
    android:textSize="18sp" />

 </LinearLayout>

<ViewAnimator
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/viewAnimator"
    android:layout_gravity="right" />

<ImageButton
    android:id="@+id/speech_btn"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/xectaicon"
    android:onClick="onClick"
    android:layout_marginTop="32dp"
    android:layout_gravity="center_horizontal|top" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="127dp"
    android:id="@+id/listView"
    android:layout_weight="1.22"
    android:background="@android:drawable/screen_background_light_transparent" />

</LinearLayout>

And activity_settings...

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:background="@drawable/onericblur">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/listSeparatorTextViewStyle"
    android:text="Settings"
    android:id="@+id/textView"
    android:layout_gravity="center_horizontal"
    android:textSize="30dp"
    android:textColor="@android:color/black" />

<TextView
    android:layout_width="291dp"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Xecta is currently in Beta being tested, you can request settings by going to the feedback section. Sorry!"
    android:id="@+id/textView2"
    android:layout_weight="0.04"
    android:layout_gravity="center_horizontal"
    android:textSize="20dp"
    android:gravity="center|top" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back to home"
    android:id="@+id/button3"
    android:onClick="onClickBack"
    android:layout_gravity="center_horizontal" />

</LinearLayout>

What could be causing the problem?!?!?

Thanks.

As suggested by Ram Kiran, it's better to have different activities for Settings / Home.

The problem with the code you have posted is that you are not populating the list with the contents when you press back. I believe it should be fixed with the following code,

public void onClickBack(View view)
{
    setContentView(R.layout.activity_main);
    ListView lv = (ListView) findViewById(R.id.listView);
    lv.setAdapter(simpleAdpt);

}

Basically when you call setContentView(layoutId) new view will be inflated from the layout and you need to do all the UI lookup, initialization again.

I dont think loading xml files repeatedly in same activity is a good one. Try to use two activities instead of loading different xml files in same activity.

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView lv = (ListView) findviewById(R.id.list);

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
                            long id)
    {

        Intent n = new Intent(getApplicationContext(),SettingsActivity.class);
        startActivity(n);
    }
}

SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Buttoon btn = (Button) findviewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
        Intent n = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(n);
         }
     });

Try out as below:

@Override
public void onResume()
{
    super.onResume();
 setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, BoundService.class);
    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

    //homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);

    name = (EditText) findViewById(R.id.etName);
    email = (EditText) findViewById(R.id.etEmail);
    mMessage = (EditText) findViewById(R.id.etAdd);
    subject = (EditText) findViewById(R.id.txtSubject);

    Button startBtn = (Button) findViewById(R.id.send);

    backB1 = (Button)findViewById(R.id.button1);
    backB2 = (Button)findViewById(R.id.button2);
    backB3 = (Button)findViewById(R.id.button3);

    //Initialize GUI elements
    setSpeakButton();

    //Initialize the speech recognizer
    createRecognizer(getApplicationContext());

    //Initialize text to speech
    myTts = TTS.getInstance(this);

    //Create bot
    bot = new Bot(this, BOTID, myTts, "assistant");

    initList();

    // We get the ListView component from the layout
    ListView lv = (ListView) findViewById(R.id.listView);


    // This is a simple adapter that accepts as parameter
    // Context
    // Data list
    // The row layout that is used during the row creation
    // The keys used to retrieve the data
    // The View id used to show the data. The key number and the view id must match
    simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});


    lv.setAdapter(simpleAdpt);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM