0

The code below works fine in ListView and I spend a few days still got no idea how to convert it into GridView. At first I try to replace ListView into GridView but failed. Anyone can help please?

Prachi
  • 2,559
  • 4
  • 25
  • 37
user1042911
  • 91
  • 2
  • 6

5 Answers5

2

For this kind of requirement better to use 'RecyclerView', instead of listview and gridview ,in recylerview one option like 'recyclerview.setLayoutManager(layoutmanager)'.

LayoutManager for listview:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());

LayoutManager for gridview:

 GridLayoutManager layoutManager = new GridLayoutManager(getActivity(),nColumns);

for more details refer to http://www.intertech.com/Blog/android-v5-lollipop-recyclerview-tutorial/

balu b
  • 282
  • 2
  • 7
0
package com.betech.bbqv2.jsonparse;
import android.app.ActionBar;

import com.betech.bbqv2.login.AndroidPHPConnectionDemo;
import com.betech.bbqv2.main.AddActivity;
import com.betech.bbqv2.main.CheckLogin;
import com.betech.bbqv2.main.DataListView;
import com.betech.bbqv2.main.MainActivity;
import com.betech.bbqv2.main.OrderHistory;
import com.betech.bbqv2.R;
import com.betech.bbqv2.main.SingleContactActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
 import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class countrymain extends Activity {

ListView mListView;
private String catid;
private String companycode="bbq";

private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;

private SharedPreferences tmploginPreferences;
private SharedPreferences.Editor tmploginPrefsEditor;
String matchguest="";

private ActionBar actionBar;
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
   // requestWindowFeature(Window.FEATURE_NO_TITLE);
   // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.country_main);  
    actionBar = getActionBar(); 
    actionBar.show();
    getActionBar().setIcon(R.drawable.actionbar_icon);
    getActionBar().setDisplayShowTitleEnabled(false);


    loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
    loginPrefsEditor = loginPreferences.edit();
    tmploginPreferences = getSharedPreferences("tmploginPrefs", MODE_PRIVATE);
    tmploginPrefsEditor = tmploginPreferences.edit();
       String login1 = loginPreferences.getString("username", "");
       String login2 = tmploginPreferences.getString("tmpusername", "");
       String match="nomatch";
       login1=login1.toLowerCase();
       login2=login2.toLowerCase();


       if(login1.equalsIgnoreCase("guest") || login2.equalsIgnoreCase("guest")){

           matchguest="guest";

       }else{
           matchguest="noguest";
       }

    catid=getIntent().getExtras().getString("cat");
   String strUrl = "http://myweb/bbq/mobile.php?catid="+catid+"&matchguest="+matchguest;



    DownloadTask downloadTask = new DownloadTask();

    // Starting the download process
    downloadTask.execute(strUrl);

    // Getting a reference to ListView of activity_main
    mListView = (ListView) findViewById(R.id.lv_countries);
    mListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) { 
      //Open the browser here

            HashMap<String,Object> map = (HashMap<String, Object>) parent.getItemAtPosition(position);      
            TextView foodcode = ((TextView) mListView.findViewById(R.id.foodcode));
            TextView foodname = ((TextView) mListView.findViewById(R.id.foodname));
            TextView fooddesc1 = ((TextView) mListView.findViewById(R.id.fooddesc1));
            TextView fooddesc2 = ((TextView) mListView.findViewById(R.id.fooddesc2));
            TextView foodprice = ((TextView) mListView.findViewById(R.id.foodprice));


        //  Toast.makeText(countrymain.this, "label is="+map.get("country")
                //  , Toast.LENGTH_SHORT).show();
        //  Toast.makeText(countrymain.this, "label is="+quantity.getText().toString()
                    //, Toast.LENGTH_SHORT).show();
            //TextView quantity = ((TextView) v.findViewById(R.id.value));



            Intent in = new Intent(getApplicationContext(),
                    SingleContactActivity.class);
            in.putExtra("foodcode", map.get("foodcode").toString());
            in.putExtra("foodname", map.get("foodname").toString());
            in.putExtra("fooddesc1", map.get("fooddesc1").toString());
            in.putExtra("fooddesc2", map.get("fooddesc2").toString());
            in.putExtra("foodprice", map.get("foodprice").toString());
            in.putExtra("imagepath", map.get("flag_path").toString());

            startActivity(in);

    }
    });

   // public void onItemClick(AdapterView<?> parent, View v,
    //      int position, long id) {
  //  mListView.setOnItemClickListener(new OnItemClickListener() {

    //    public void onItemClick(AdapterView adapterView, View view, int position, long id) {
        //    SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();
         //   ListView currentLv = (ListView) view;

          //  Object item = adapter.getItem(position);
            //Do some more stuff here and launch new activity


          //}
        //});


}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url 
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url 
            urlConnection.connect();

            ///////////////////////////////Newly added
            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();

           // InputStream is = null;
            Log.d("response code=",String.valueOf(responseCode));
            if (responseCode >= 400) {
                iStream = urlConnection.getErrorStream();
            } else {
                //is = urlConnection.getInputStream();
                 iStream = urlConnection.getInputStream();
            }

            /////////////////////////////////////////////////

            // Reading data from url 
           // iStream = urlConnection.getInputStream();<---original

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

    }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
    }finally{
            iStream.close();
    }

    return data;
}



/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
    String data = null;
            @Override
            protected String doInBackground(String... url) {
                    try{
                        data = downloadUrl(url[0]);


                    }catch(Exception e){
                        Log.d("Background Task",e.toString());
                    }
                    return data;
            }

            @Override
            protected void onPostExecute(String result) {

                    // The parsing of the xml data is done in a non-ui thread 
                    ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

                    // Start parsing xml data
                    listViewLoaderTask.execute(result);                        

            }
}

/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    JSONObject jObject;

    // Doing the parsing of xml data in a non-ui thread 
    @Override
    protected SimpleAdapter doInBackground(String... strJson) {


        try{

            //Toast.makeText(countrymain.this, "URL="+strJson[0], Toast.LENGTH_SHORT).show();
            jObject = new JSONObject(strJson[0]);




            CountryJSONParser countryJsonParser = new CountryJSONParser();
            countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("JSON Exception1",e.toString());
        }

        // Instantiating json parser class
        CountryJSONParser countryJsonParser = new CountryJSONParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try{
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }          

        // Keys used in Hashmap 
       //String[] from = { "country","flag","details"};
        String[] from = { "foodcode","foodname","fooddesc1","fooddesc2","foodprice","flag"};

        // Ids of views in listview_layout
       // int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
        int[] to = { R.id.foodcode,R.id.foodname,R.id.fooddesc1, R.id.fooddesc2,R.id.foodprice,R.id.iv_flag};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item         
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);  


     //   CheckLogin checknow = new CheckLogin ();

    //  String guestnot=checknow.checklogin();
    //  Log.d("Match=",guestnot);
    //  if(guestnot.equals("match")){
    //      
        //}

        return adapter;
    }

    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        mListView.setAdapter(adapter);

    //  Toast.makeText(countrymain.this, "label is="+adapter.getCount()
      //        , Toast.LENGTH_SHORT).show();


        for(int i=0;i<adapter.getCount();i++){
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String imgUrl = (String) hm.get("flag_path");


            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("flag_path",imgUrl);
            hm.put("position", i);

            // Starting ImageLoaderTask to download and populate image in the listview 
            imageLoaderTask.execute(hm);
        }
    }       
}

/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        String imgUrl = (String) hm[0].get("flag_path");
        int position = (Integer) hm[0].get("position");

        URL url;
        try {
            url = new URL(imgUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url                
            urlConnection.connect();

            // Reading data from url 
            iStream = urlConnection.getInputStream();

            // Getting Caching directory 
            File cacheDirectory = getBaseContext().getCacheDir();

            // Temporary file to store the downloaded image 
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".jpg");               

            // The FileOutputStream to the temporary file
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            // Creating a bitmap from the downloaded inputstream
            Bitmap b = BitmapFactory.decodeStream(iStream);             

            // Writing the bitmap to the temporary file as png file
            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);              

            // Flush the FileOutputStream
            fOutStream.flush();

            //Close the FileOutputStream
            fOutStream.close();             

            // Create a hashmap object to store image path and its position in the listview
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            // Storing the path to the temporary image file
            hmBitmap.put("flag",tmpFile.getPath());

            // Storing the position of the image in the listview
            hmBitmap.put("position",position);              

            // Returning the HashMap object containing the image path and position
            return hmBitmap;                


        }catch (Exception e) {              
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {
        // Getting the path to the downloaded image
        String path = (String) result.get("flag");          

        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");

        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

        // Getting the hashmap object at the specified position of the listview
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);   

        // Overwriting the existing path in the adapter 
        hm.put("flag",path);

        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged(); 
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    //menuInflater.inflate(R.layout.menu, menu);

    menuInflater.inflate(R.menu.activity_main_actions, menu);

    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
     switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.action_setting1s:
            Intent m= new Intent(getApplicationContext(),MainActivity.class);
            startActivity(m);
          break;
        // action with ID action_settings was selected
        case R.id.action_setting2s:
            Intent j = new Intent(getApplicationContext(),DataListView.class);
            startActivity(j);
          break;
        case R.id.action_setting3s:
             // Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
              //    .show();
             Intent k = new Intent(getApplicationContext(),OrderHistory.class);
                startActivity(k);
              break;
        case R.id.action_setting4s:
             // Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
              //    .show();
            Intent intent = new Intent(getApplicationContext(),AndroidPHPConnectionDemo.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        //  moveTaskToBack(true);
          //  android.os.Process.killProcess(android.os.Process.myPid());
            //System.exit(0);
              break;
        default:
          break;
        }

        return true;


}   }
user1042911
  • 91
  • 2
  • 6
0
<?xml version="1.0" encoding="utf-8"?>//    gridView.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<GridView 
    android:layout_height="wrap_content" 
    android:id="@+id/gridView1" 
    android:layout_width="match_parent" 
    android:numColumns="2"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp">
</GridView>

<?xml version="1.0" encoding="utf-8"?>   //  grid_view_item.xml
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    android:gravity="center"   
    android:paddingTop="10dp"  
    android:paddingBottom="10dp">  

    <ImageView  
        android:id="@+id/imageView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:src="@drawable/button01" />  

    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="TextView" />  

user1042911
  • 91
  • 2
  • 6
0

One attribute should be added for getting GridView other than replacing ListView with GridView.

That is,

android:numColumns="auto_fit"

also replace ListView with GridView in your java file.

activesince93
  • 1,716
  • 17
  • 37
0

I changed the line from SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

to

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.grid_view_item, new String[] {"flag","foodname","fooddesc1","foodprice"},new int[] {R.id.imageView1,R.id.textView1,R.id.textView2,R.id.textView3});

and works ok now. many thanks!

user1042911
  • 91
  • 2
  • 6