Search code examples
javaandroidlistviewnavigation-drawerbaseadapter

App will not run the first time but when item in menu is clicked it runs


I read data from json file to an adapter and in the main.java under oncreate, when I try runing it,it doest show anything.

I tried the same code under menu onclick and it works, I want it to appear when the app is first runed.

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    String url = "myjsonurl.php";
    JSONArray jArray;
    ProgressDialog dialog;
    ListView mycustomlist = null;
    WebView mywebview =null;
    CustomAdapter myadapter = null;

    ArrayList<news> mydatalist = new ArrayList<news>();
    ArrayList<news> maşetData = new ArrayList<news>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myadapter = new CustomAdapter(this, mydatalist);
        mycustomlist = (ListView)findViewById(R.id.listview);
        mycustomlist.setAdapter(myadapter);
        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading....");
        dialog.show();

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String string) {
                parseJsonData(string);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                dialog.cancel();
            }
        });

        RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
        rQueue.add(request);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


       /* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
*/



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    public void parseJsonData(final String jsonString) {

        try {
            jArray = new JSONArray(jsonString);

            for(int i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);
                news news1 = new news();

                news1.setTitle(jObject.getString("title"));
                news1.setContent(Html.fromHtml(jObject.getString("content")));
                news1.setDate(jObject.getString("date"));
                news1.setImage("http://www.bolgegundem.com/d/news/" + jObject.getString("image").concat(".jpg"));
                news1.setId(jObject.getString("id"));
                news1.setCategory(jObject.getString("category"));
                news1.set__comment_count(jObject.getString("__comment_count"));
                news1.setHeadline(jObject.getString("headline"));

                mydatalist.add(news1);




                //  http://www.bolgegundem.com/d/gallery/81_2.jpg
               /* images.add("http://www.bolgegundem.com/d/gallery/" + id +  "_" + imgUrl.replace(",", ".jpg") );*/
                // al.add(title);
                //imagelinks[i] = "http://www.bolgegundem.com/d/gallery/" + id + "_" + i + ".jpg";

            }


            // ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, al);

            //listview.setAdapter(adapter);

            // listview.setBackgroundColor(rgb(0, 255, 255));
              /*  listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if(i < links.length){
                        Uri uri = Uri.parse(links[i]);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    }
                }
            });*/
            if (dialog.isShowing()){
                dialog.dismiss();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            dialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.manşet) {
            // Handle the camera action
        } else if (id == R.id.Anasayfa) {

            myadapter = new CustomAdapter(this, mydatalist);
            mycustomlist = (ListView)findViewById(R.id.listview);
            mycustomlist.setAdapter(myadapter);


        } else if (id == R.id.ajansTv) {

        } else if (id == R.id.foto) {

        } else if (id == R.id.gundem) {

        } else if (id == R.id.siyaset) {

        }else if (id ==R.id.Ekonomi ){


        }else if (id ==R.id.spor ){


        }else if (id ==R.id.saglik ){

        }else if (id ==R.id.nav_share ){


        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

My adapter class is here

public class CustomAdapter extends BaseAdapter {

    Context mycontext = null;
    ArrayList<news> mydatalist;

    public CustomAdapter(Context mycontext, ArrayList<news> mydatalist)
    {

        this.mycontext = mycontext;
        this.mydatalist = mydatalist;

    }

    @Override
    public int getCount() {
        return this.mydatalist.size();
    }

    @Override
    public Object getItem(int position) {
        return this.mydatalist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater myinflater = (LayoutInflater)mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewHolder myholder = null;
        if(convertView == null)
        {
            convertView = myinflater.inflate(R.layout.customlayout, null);

            myholder = new ViewHolder();
            myholder.mytextview1 = (TextView)convertView.findViewById(R.id.mytextview1);
            myholder.mytextview2 = (TextView)convertView.findViewById(R.id.mytextview2);
            myholder.mytextview3 = (TextView)convertView.findViewById(R.id.mytextview3);
            myholder.myimageview1 = (ImageView)convertView.findViewById(R.id.imageView);

            convertView.setTag(myholder);
        }
        else
        {
            myholder = (ViewHolder)convertView.getTag();
        }


        myholder.mytextview1.setText(mydatalist.get(position).getTitle());
        myholder.mytextview2.setText(mydatalist.get(position).getContent());
        myholder.mytextview3.setText(mydatalist.get(position).getDate());
        myholder.myimageview1.setImageResource(R.drawable.bolgegundem);
        new DownloadImageTask(myholder.myimageview1).execute(mydatalist.get(position).getImage());

        return convertView;
    }

    static class ViewHolder
    {
           public TextView mytextview1;
           public TextView mytextview2;
           public TextView mytextview3;
           public ImageView myimageview1;
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
}

How can I solve this?


Solution

  • Put the three lines

        myadapter = new CustomAdapter(this, mydatalist);
            mycustomlist = (ListView)findViewById(R.id.listview);
            mycustomlist.setAdapter(myadapter);
    

    in this method:

     @Override
     public void onResponse(String string) {
        parseJsonData(string);
        // put them here
     }
    

    This will work because it populates the list after the data is parsed add then adds it to the adapter. If you add the list to the adapter in OnCreate, the onResponse method will run later (when the data is returned) and the list will be empty.