简体   繁体   中英

Local variable may not been initialized

How do i initialized autoComplete? I cant use it with AutoCompleteTextView because it'll tell me that local variable is duplicated. Tried declaring it static as well but its not permitted.

Please advice!

public class Search extends Activity {
    public void onCreate(Bundle savedInstanceSate) {
        final int autoComplete;
        super.onCreate(savedInstanceSate);
        setContentView(R.layout.searchshop);

         //The duplicate im talking about
        AutoCompleteTextView autoCompletee = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
        autoCompletee.setAdapter(adapter); 
        autoCompletee.setThreshold(1);
        autoCompletee.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)  {
                Intent intent;
                int index=999;
                for(int i=0;i<shops.length;i++) {
                        //The local variable autoComplete may not been initialized
                    if(shops[i].equals(Integer.toString(autoComplete))) {
                        index=i;
                        break;
                    }
                }
                switch(index) {
                    case 0:
                        intent=new Intent(Search.this, Adidas.class);
                        startActivity(intent);
                        break;
                    case 1:
                        intent=new Intent(Search.this, Affin.class);
                        startActivity(intent);  
                        break; 
                }
            }
        }); 
    }

    static final String[] shops = new String[] {
                "Adidas", "Affin Bank", "Alam Art", "Al Amin"
    };
}

Modifying the int autoComplete to be static , final , etc won't matter one bit because the compiler is complaining about the fact that you already have a variable called "autoComplete". In your actual code example, you named your AutoCompleteTextView "autoCompletee" with two e's which is different from autoComplete so that will work. But I'd recommend using more meaningful variable names like int autoCompleteValue or something along those lines. Either way, the problem is that you have variables colliding. Once you have a variable in scope with a certain name, you cannot use that name again...

You have autoComplete field as local variable, which need to set to some default value.

just set final int autoComplete=0;

Move this as third statement in code, first two statements should be super.... and setContent(...)

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