6 / 6 / 0
Регистрация: 29.06.2012
Сообщений: 184
1

Ошибка при выборе Item в ListView

19.07.2013, 12:55. Показов 960. Ответов 4
Метки нет (Все метки)

Здравствуйте уважаемые форумчане.
Не могу определить где ошибся. У меня есть ListView где несколько Item-ов при клике на любой из них должно запустится активити по Id Item-a. У мена все работало нормально, но вдруг перестало. Теперь при нажатии на любой из Item-ов открывается самый последний по списку, потом перед последний... и так до нужного Itema.
Помогите пож-ста разобраться. Заранее благодарю

Вот весь код. Думаю ошибка моя где то в Case-ах?

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package com.example.helper;
 
import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
public class taarifs extends Activity {
    private List<Car> mycars = new ArrayList<Car>();
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.testo);
        
        populateCarList();
        populateListView();
        registerClickCallback();
        
        
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
        menu.add("Настройки");
        menu.add("Инструкция");
        menu.add("Обновить");
        menu.add("Выход");
        return super.onCreateOptionsMenu(menu);
        }
 
    private void populateCarList() {
        mycars.add(new Car("Салом", 18, R.drawable.nexti, " " ));
        mycars.add(new Car("Офарин", 7, R.drawable.nexti, "Тариф в архиве" ));
        mycars.add(new Car("Санам", 9, R.drawable.nexti, "Тариф в архиве" ));
        mycars.add(new Car("Реальный", 3, R.drawable.nexti, "Тариф в архиве" ));
        mycars.add(new Car("Навруз", 23, R.drawable.nexti, "Тариф в архиве" ));
        mycars.add(new Car("Ачоиб", 5, R.drawable.nexti, " " ));
        mycars.add(new Car("City", 30, R.drawable.nexti, " " ));
        mycars.add(new Car("Аввалин", 1, R.drawable.nexti, " " ));
        mycars.add(new Car("Фоиданок", 2, R.drawable.nexti, " " ));
        mycars.add(new Car("Next", 3, R.drawable.nexti, " " ));
        
        
    }
    private void populateListView() {
        ArrayAdapter<Car> adapter=new MyListAdapter();
        ListView list=(ListView) findViewById(R.id.carsListView);
        list.setAdapter(adapter);
        
        
    }
    
    private void registerClickCallback() {
        ListView list =(ListView) findViewById(R.id.carsListView);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
 
            @Override
            public void onItemClick(AdapterView<?> parent, View viewCliced,
                    int position, long id) {
                Car clickedCar =mycars.get(position);
                String message="Вы выбрали объкт № " + position
                    + " наименование " + clickedCar.getMake();
                Toast.makeText(taarifs.this, message,Toast.LENGTH_LONG).show();
            // Вот тут по моему надо что то написать чтоб второе активити запустилось, но я незнаю что
                
                 switch ((int)id) {
                    case 0:
                       
                        Intent intent = new Intent(taarifs.this, tarifsview.class);
                        taarifs.this.startActivity(intent);
                        
                        
                        //String encodedHash = Uri.encode("#");
                        //String ussd = "*" + encodedHash + "100" + encodedHash;
                        //startActivityForResult(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussd)), 1);
                    case 1:
                        Intent intent1 = new Intent(taarifs.this, ofarin.class);
                        taarifs.this.startActivity(intent1);
                    case 2:
                        Intent sanam = new Intent(taarifs.this, sanam.class);
                        taarifs.this.startActivity(sanam);
                        
                    case 3:
                        Intent realniy = new Intent(taarifs.this, realniy.class);
                        taarifs.this.startActivity(realniy);
                    case 4:
                        Intent navruz = new Intent(taarifs.this, navruz.class);
                        taarifs.this.startActivity(navruz);
                   case 6:
                    Intent city = new Intent(taarifs.this, city.class);
                        taarifs.this.startActivity(city);
                    }
                
                
                
                //Intent intent = new Intent(MainActivity.this, tarifsall.class);
                //MainActivity.this.startActivity(intent);
            
            }
            
            
        });
        
    }
    
    private class MyListAdapter extends ArrayAdapter<Car>{
        
        public MyListAdapter(){
            super (taarifs.this, R.layout.item_view, mycars);
                    }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
             
            View itemView=convertView;
            if(itemView==null){
                itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
                
            }
            
            Car currentCar=mycars.get(position);
            
            
            ImageView imageView=(ImageView)itemView.findViewById(R.id.item_icon);
            imageView.setImageResource(currentCar.getIconID());
            
            TextView makeText=(TextView)itemView.findViewById(R.id.item_txtMake);
            makeText.setText(currentCar.getMake());
            
            TextView yearText=(TextView)itemView.findViewById(R.id.item_txtYear);
            yearText.setText("" + currentCar.getYear());
                    
            TextView conditionText=(TextView)itemView.findViewById(R.id.item_txtCondition);
            conditionText.setText(currentCar.getcondition());
            
            return itemView;
            
        }
    
    
 
    
    }
    
 
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
19.07.2013, 12:55
Ответы с готовыми решениями:

C# ListView ошибка при выборе item
Здравствуйте! При повторном выборе item выходит ошибка: InvalidArgument=Значение '0'...

При выборе первого Item в combobox показывать edit1
Всем привет, может кто поможет мне разобраться с Case?) На форму добавил компонент ComboBox1 и 4...

Удаление Item'a из ListView при пустом SubItem'e
Всем доброго времени суток! Суть проблемы: имеется ListView, в котором несколько колонок....

Смена изображения Item'а в ListView при наведение мыши
Здравствуйте. Как можно в ListView при наведении мыши менять иконку Item'а? Если же мышь не...

4
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
20.07.2013, 00:36 2
где return'ы с кейсов подевали?
0
6 / 6 / 0
Регистрация: 29.06.2012
Сообщений: 184
20.07.2013, 16:24  [ТС] 3
Цитата Сообщение от V0v1k Посмотреть сообщение
где return'ы с кейсов подевали?
Изначально их не было. Дело в том что я сначала делал, для одного item-a. Был только один case потом добавил другие и получилось каша. Можете подсказать, где ретурн написать и что именно написать чтоб ошибка исправилась?. Спасибо
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
20.07.2013, 22:20 4
извиняюсь, имел ввиду break
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
case 0:
                       
                        Intent intent = new Intent(taarifs.this, tarifsview.class);
                        taarifs.this.startActivity(intent);
                        
                        
                        //String encodedHash = Uri.encode("#");
                        //String ussd = "*" + encodedHash + "100" + encodedHash;
                        //startActivityForResult(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussd)), 1);
                        break;
                    case 1:
                        Intent intent1 = new Intent(taarifs.this, ofarin.class);
                        taarifs.this.startActivity(intent1);
                        break;
                    case 2:
                        Intent sanam = new Intent(taarifs.this, sanam.class);
                        taarifs.this.startActivity(sanam);
                        break;                        
                    case 3:
                        Intent realniy = new Intent(taarifs.this, realniy.class);
                        taarifs.this.startActivity(realniy);
                        break;
                    case 4:
                        Intent navruz = new Intent(taarifs.this, navruz.class);
                        taarifs.this.startActivity(navruz);
                        break;
                   case 6:
                    Intent city = new Intent(taarifs.this, city.class);
                        taarifs.this.startActivity(city);
                        break;
                    }
1
6 / 6 / 0
Регистрация: 29.06.2012
Сообщений: 184
21.07.2013, 00:34  [ТС] 5
V0v1k, Огромное спаибо! благодарен!
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.07.2013, 00:34
Помогаю со студенческими работами здесь

Как найти id записи в SQlite таблице при клике на кнопку расположенную в Listview item?
привет ! подскажите пожалуйста решение((( Кейс: у меня есть листвью , который выводит записи...

При выборе узла treeView не отображается информация из БД в listView
Здравствуйте господа программисты! Столкнулся с следующей проблемой. При выборе узла treeView не...

Обновление столбца listview при выборе значения в combobox
Подскажите, пожалуйста, как сделать? чтобы при выборе соответствующего значения в combobox...

При выборе узла TreeView его подузлы записать в ListView
Как сделать, что бы при выборе какого-нибудь узла TreeView его подузлы отображались в ListView?

При открытии второй формы в combobox.text отобразить выделенный Item в listview из первой формы
на первой форме listbox и кнопка(listbox привязан к бд).При нажатии на кнопку открывается вторая...

TabControl + ListView или как сделать вывод информации при выборе TabPage?
Здравствуйте!Такой вопрос.Есть TabControl в котором создал 2 вкладки TabPage.В самом TabPage лежит...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru