-2

I am trying to select the first index in listview on first load onCreate. I've try the listView.setSelection(0) but some error occur. this is my code...

public class QandAPractice extends AppCompatActivity {
String qsid;
ListView listView;
ArrayList<String> myqid;
RadioButton r1,r2,r3,r4;
String txtcontent, txtTimer,txtAnskey,txtImg, txtA, txtB, txtC, txtD, txtID;
private static final String TAG_QID = "id";
private static final String TAG_TITLE = "content";
private static final String TAG_TIMER = "timer";
private static final String TAG_IMAGE = "images";
private static final String TAG_QSID = "qsid";
private static final String TAG_KEY = "key";
private static final String TAG_A = "A";
private static final String TAG_B = "B";
private static final String TAG_C = "C";
private static final String TAG_D = "D";
ArrayList<HashMap<String, String>> questions;
Dialog quizDialog;
public int i = 60;
public int loadindex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qand_apractice);
    questions = new ArrayList<>();
    myqid = new ArrayList<>();
    Bundle b = getIntent().getExtras();
    setTitle(b.getString("subject"));
    qsid = b.getString("qsid");
    quizDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    listView = findViewById(R.id.lvquestions);
    getJSON(Constants.ROOT_URL+"mobile_question_index.php?qsid="+qsid);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            txtID = ((TextView) view.findViewById(R.id.quiz_id)).getText()
                    .toString();
            txtcontent = ((TextView) view.findViewById(R.id.quiz_content)).getText()
                    .toString();
            txtTimer = ((TextView) view.findViewById(R.id.quiz_timer)).getText()
                    .toString();
            txtAnskey = ((TextView) view.findViewById(R.id.quiz_key)).getText()
                    .toString();
            txtA = ((TextView) view.findViewById(R.id.quiz_A)).getText()
                    .toString();
            txtB = ((TextView) view.findViewById(R.id.quiz_B)).getText()
                    .toString();
            txtC = ((TextView) view.findViewById(R.id.quiz_C)).getText()
                    .toString();
            txtD = ((TextView) view.findViewById(R.id.quiz_D)).getText()
                    .toString();
            txtImg = ((TextView) view.findViewById(R.id.quiz_image)).getText()
                    .toString();
            showQuiz();

        }
    });
    listView.setSelection(0);
    listView.getSelectedView().setSelected(true);
}
private void getJSON(final String urlWebService) {

    class GetJSON extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                loadIntoListView(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }
        }
    }
    GetJSON getJSON = new GetJSON();
    getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);
    //String[] question = new String[jsonArray.length()];

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.getJSONObject(i);
        String id = obj.getString(TAG_QID);
        String content = obj.getString(TAG_TITLE);
        String image = obj.getString(TAG_IMAGE);
        String a = obj.getString(TAG_A);
        String b = obj.getString(TAG_B);
        String c = obj.getString(TAG_C);
        String d = obj.getString(TAG_D);
        String key = obj.getString(TAG_KEY);
        String timer = obj.getString(TAG_TIMER);
        HashMap<String, String> map = new HashMap<String, String>();

        map.put(TAG_QID,id);
        map.put(TAG_TITLE,content);
        map.put(TAG_IMAGE,image);
        map.put(TAG_A,a);
        map.put(TAG_B,b);
        map.put(TAG_C,c);
        map.put(TAG_D,d);
        map.put(TAG_KEY,key);
        map.put(TAG_TIMER,timer);
        myqid.add(id);
        questions.add(map);
    }
    // ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
    SimpleAdapter adapter = new SimpleAdapter(
            QandAPractice.this, questions,
            R.layout.quizlayout, new String[]{TAG_QID,
            TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
            new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
                    R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/*    AtomicReference<ListAdapter> la =
            new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/

    listView.setAdapter(adapter);
}

this is the Error fetch in debug logcat..

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setSelected(boolean)' on a null object reference
    at com.example.jhan08.engineeringexclusivereviewer.QandAPractice.onCreate(QandAPractice.java:90)
    at android.app.Activity.performCreate(Activity.java:6351)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)

I've read some thread that has the same issue like mine. They use adapter to fix the issue but still in my case this error still occur. Any help is much appreciated.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Tim Jhan
  • 1
  • 3

2 Answers2

0

Do Your Selection after you set Your Adapter to the Listview

private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];

for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject obj = jsonArray.getJSONObject(i);
    String id = obj.getString(TAG_QID);
    String content = obj.getString(TAG_TITLE);
    String image = obj.getString(TAG_IMAGE);
    String a = obj.getString(TAG_A);
    String b = obj.getString(TAG_B);
    String c = obj.getString(TAG_C);
    String d = obj.getString(TAG_D);
    String key = obj.getString(TAG_KEY);
    String timer = obj.getString(TAG_TIMER);
    HashMap<String, String> map = new HashMap<String, String>();

    map.put(TAG_QID,id);
    map.put(TAG_TITLE,content);
    map.put(TAG_IMAGE,image);
    map.put(TAG_A,a);
    map.put(TAG_B,b);
    map.put(TAG_C,c);
    map.put(TAG_D,d);
    map.put(TAG_KEY,key);
    map.put(TAG_TIMER,timer);
    myqid.add(id);
    questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
        QandAPractice.this, questions,
        R.layout.quizlayout, new String[]{TAG_QID,
        TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
        new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
                R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/*    AtomicReference<ListAdapter> la =
        new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/

  listView.setAdapter(adapter);
  listView.setSelection(0);
  listView.getSelectedView().setSelected(true);

 }
Faiz Mir
  • 599
  • 5
  • 16
  • thanks for the help sir @Faiz Mir. one concern sir the error is keep pointing to this line listView.getSelectedView().setSelected(true); does this necessary to view the content of the first index? – Tim Jhan Oct 12 '18 at 04:34
  • what you are trying to achieve ? listView.getSelectedView().setSelected(true) comment this line and check – Faiz Mir Oct 12 '18 at 04:36
  • Yes sir I've try to comment that one out but still to display or even toast of data came from the first item in listview, and no error has been pop up. – Tim Jhan Oct 12 '18 at 04:47
  • Accept the answer if its help – Faiz Mir Oct 12 '18 at 04:48
0

I think I got the main issue you have faced. You try to select an item before populating the list view. You need to set this after adapter added on the listview. Add this lines after adding the adapter.

listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);

or use

listView.setAdapter(adapter);
listView.setItemChecked(0, true)

This will show a toast message for first opening. This should be added after the adapter set.

Iterator myVeryOwnIterator = questions.get(0).keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
    String key=(String)myVeryOwnIterator.next();
    String value=(String)meMap.get(key);
    Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
  • thanks for sir but can you site how to is going to display or toast data? i mean if i run the activity it will automatically toast the value of the first item in listview. – Tim Jhan Oct 12 '18 at 08:32
  • Which content do you want to show? You already have the question list that contains map object. You can easily get the content from map object. – Faysal Ahmed Oct 12 '18 at 09:30
  • thanks sir Faysal Ahmed, I've already find the solution with this code listView.performItemClick(listView.getAdapter().getView( loadindex, null, null), loadindex, listView.getItemIdAtPosition(loadindex)); credit to the owner. – Tim Jhan Oct 12 '18 at 10:47
  • This code will work but this is not a correct way to do this. You already have a list so why you click an item and get the list? – Faysal Ahmed Oct 12 '18 at 11:00