How to create custom gridview (Like matrix structure ) in Android - android

I want to create a matrix like gridview say 10x20 matrix
we want to specify the number of rows and column of the View ie 10x20
if the screen is low it should scroll to horizontally and vertically
for example the image below describe the Matrix Gridview
Each cell represent
(0,0) (0,1) etc...
(1,0) (1,1) etc..
How can generate this type of view?
Advance Thanks ....!!!

try this:
GridViewCustomAdapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
public class GridViewCustomAdapter extends BaseAdapter {
ArrayList<String> items;
static Activity mActivity;
private static LayoutInflater inflater = null;
public GridViewCustomAdapter(Activity activity, ArrayList<String> tempTitle) {
mActivity = activity;
items = tempTitle;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public final int getCount() {
return items.size();
}
#Override
public final Object getItem(int position) {
return items.get(position);
}
#Override
public final long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = null;
v = inflater.inflate(R.layout.item, null);
Button tv = (Button) v.findViewById(R.id.button);
tv.setText(items.get(position));
return v;
}
}
gridview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#android:color/white"
android:orientation="vertical" >
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="20dip"
android:gravity="center"
android:horizontalSpacing="2dp"
android:verticalSpacing="2dp"
android:numColumns="20"
android:stretchMode="columnWidth" >
</GridView>
</LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button"
android:layout_width="80dip"
android:layout_height="80dip"
android:textSize="10sp"
android:background="#android:color/holo_blue_light"
android:textColor="#android:color/black"
android:textStyle="bold" />
GridViewActivity
public class GridViewActivity extends Activity {
private GridView list;
ArrayList<String> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
for (int i = 0; i < 10; i++) {
for(int j=0;j<20;j++)
data.add(i+"-"+j);
}
GridViewCustomAdapter adapter = new GridViewCustomAdapter(this, data);
list = (GridView) findViewById(R.id.grid_view);
list.setAdapter(adapter);
}
}
output :

This can be achieved by GridLayout and dynamic Cell creation
/*
*
* Copyright 2012 Jess Anders
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridLayout gl;
TextView[] text;
int item;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gl = new GridLayout(MainActivity.this);
gl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
gl.setOrientation(0);
gl.setColumnCount(11);
gl.setRowCount(3);
text = new TextView[100];
ScrollView sv = new ScrollView(this);
sv.setScrollbarFadingEnabled(false);
HorizontalScrollView scrolview = new HorizontalScrollView(this);
scrolview.setScrollbarFadingEnabled(false);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.addView(sv);
sv.addView(scrolview);
scrolview.setHorizontalScrollBarEnabled(true);
setContentView(linearLayout);
for (int i = 0; i < 100; i++) {
for (int j = 0; i < 10; j++) {
text[i] = new TextView(MainActivity.this);
text[i].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text[i].setText(String.valueOf(i) + "," + String.valueOf(j));
text[i].setTextSize(25);
text[i].setPadding(50, 25, 10, 25);
text[i].setOnClickListener(new View.OnClickListener() {
int pos = item;
public void onClick(View v) {
Toast.makeText(getBaseContext(), pos + " Clicked",
Toast.LENGTH_SHORT).show();
}
});
gl.addView(text[i]);
}
}
scrolview.addView(gl);
}
}
This is not the straight solution but... i think i need to customize the GridView which i do`nt know currently

hi this is one code that i've created to do one matrix of buttons "x"
package com.example.andre.aplicacaocalibracaov2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
GridView gridView;
List<String> lstSource = new ArrayList<>();
String[] array_caracteres={
"x"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpList();
GridView gridView = (GridView) findViewById(R.id.gridView);
//é a classe gridadapter
GridAdapter adapter = new GridAdapter(lstSource,MainActivity.this);
gridView.setAdapter(adapter);
}
public void setUpList() {
for (String item : array_caracteres)
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++)
lstSource.add(item);
}
}
}
GridAdapter.java
package com.example.andre.aplicacaocalibracaov2;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.List;
public class GridAdapter extends BaseAdapter {
private Context context;
List<String> lstSource;
public GridAdapter(List<String>lstSource, Context context){
this.lstSource = lstSource;
this.context=context;
}
#Override
public int getCount() {
return lstSource.size();
}
#Override
public Object getItem(int position) {
return lstSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Button button;
if(convertView ==null){
button = new Button(context);
button.setLayoutParams(new GridView.LayoutParams(85,85));
button.setPadding(8,8,8,8);
button.setText(lstSource.get(position));
button.setBackgroundColor(Color.YELLOW);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Toast.makeText(context,button.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
}
else
button=(Button)convertView;
return button;
}
}
the xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity"
>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridView"
android:columnWidth="30dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="4dp"
android:horizontalSpacing="4dp"
android:gravity="center"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Good luck !!

Related

Android runtime eror: the app suddenly stops

My app is to perform ListView. When it was running, the error message notified that "Unfortunately, App has stopped". Here is my code.
package com.example.admin.customadapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Nation>nationifo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.ListViewNation);
nationifo = new ArrayList<>();
nationifo.add(new Nation("VietNam",1945));
nationifo.add(new Nation("Malaysia",1975));
nationifo.add(new Nation("Laos",1943));
NationAdapter adp = new NationAdapter(
MainActivity.this,
R.layout.nation_list,
nationifo
);
listView.setAdapter(adp);
}
}
Nation.java
package com.example.admin.customadapter;
public class Nation {
public String name;
public Integer year;
public Nation(String Name, Integer Year){
Name = name;
Year = year;
}
}
NationAdapter.java
package com.example.admin.customadapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class NationAdapter extends BaseAdapter {
Context mycontext;
int mylayout;
List<Nation>arrayNation;
public NationAdapter (Context context, int layout, List<Nation>nationList){
mycontext = context;
mylayout = layout;
arrayNation = nationList;
}
public int getCount() {
return arrayNation.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(mylayout,null);
TextView txtv1 = (TextView) convertView.findViewById(R.id.textView);
txtv1.setText(arrayNation.get(position).name);
TextView txtv2 =(TextView) convertView.findViewById(R.id.textView2);
txtv2.setText(String.valueOf(arrayNation.get(position).year));
return convertView;
}
}
nation_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background = "#ffffff">
<TextView
android:textColor="#ff0400"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/textView" />
<TextView
android:textColor="#0022ff"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2" />
</LinearLayout>
My Android Studio is 2.2. But I don't think that this version is diferrent to another.
try to use the following
convertView = inflater.inflate(mylayout,parent,false);
instead of
convertView = inflater.inflate(mylayout,null);

How to add Listeners of Dynamic Check Boxes in Simple Adapter

I have dynamic CheckBoxes and now I want to check which CheckBox clicked or not
AdditionalInformation.Java File Here Simple Adapter is defined :
package com.example.ahmad.cvbuilder21;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AdditionalInformation extends ActionBarActivity {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_infromation);
cb=(CheckBox)findViewById(R.id.additionalchk);
ABC s = ABC.getSingletonObject();
String[][] str = s.getString();
ListView lv=((ListView)findViewById(R.id.additionallist));
String[] additionalOptions={"Add your Picture","Add Experince / Project","Add Reference","Add Skills / Languages"};
String[] txtViewNames={"options"};
List<HashMap<String,String>>list=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < additionalOptions.length; i++) {
HashMap<String, String> map= new HashMap<String, String>();
map.put("options", additionalOptions[i]);
list.add(map);
}
SimpleAdapter simpleAdpt = new SimpleAdapter(this, list, R.layout.mylayout2,txtViewNames , new int[] {R.id.additionaltxt1});
lv.setAdapter(simpleAdpt);
}
public void additionalData(View view1)
{
if(cb.isChecked())
{
cb.findViewById(R.id.additionalchk).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast toast = Toast.makeText(getApplicationContext(), "Checked",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();
}
}
);
}
else{}
}
}
AdditionalInformation.xml file: where additionalData function is called to
check which CheckBox clicked.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Additional Options:"
android:id="#+id/additionalBtn"
/>
<ListView
android:layout_below="#id/additionalBtn"
android:layout_centerHorizontal="true"
android:id="#+id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
<Button
android:layout_below="#id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to CV"
android:onClick="additionalData"
/>
</RelativeLayout>
mylayout2.xml file where I define the controls for simple adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/additionaltxt1"
/>
<CheckBox
android:layout_alignParentRight="true"
android:layout_alignRight="#id/additionaltxt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="#+id/additionalchk"
/>
</RelativeLayout>
What you actually need to do is create a custom adapter. In that custom you could listen for checkbox event at the right position.
Here is an example:
public class ListEmployeesAdapter extends BaseAdapter {
public List<Employees> items;
Context c;
public ListEmployeesAdapter(Context c, List<Employees> items) {
this.c = c;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
c.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.employee_item, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(items.get(position).name);
name.setOnCLickListener(new OnClickListener(){
#Override
public void onClick(){
//listen to the click
}
});
return convertView;
}
}
Just replace the the layout with you layout and call checkbox instead of TextView and you are good to go.

set a listener for widgets in items of a listview

I meet a problem developing an android project.
Using adapter, I place many items in a ListView, and there is an ImageButton in each item. Now I want to set a click listener for these ImageButtons. What should I do?
This achieves your desired result. Its functionality is the button itself has a click response different from the container, which also has a response.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Toast.makeText( MainActivity.this,
"List item clicked",
Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
items.add( "item3");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
ListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.List;
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
Toast.makeText( context,
"ImageButton clicked",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="28sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:src="#drawable/emo_im_cool" />
</RelativeLayout>
list.xml
<?xml version="1.0" encoding="utf-8" ?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list" />
Try it out and hopefully you can see what's going on to learn what you need

Probably a simple issue with custom layouts: ImageView TextView = GridView

I am working on my first "professional" (ie, full-functional, bug-free, presentable) Android application, and I'm having some problems with Android layouts.
In particular, I have a gridView that I have inflated with a layout that has an ImageView, a TextView, and a hidden TextView (visibility set to "gone").
I have an "Image not found" image that is 115 x 115. The other images ("found") are similarly 115 x 115. They're all JPEGs.
The problem is that nothing's lining up. The text is constrained to under 17 characters. So I would think that the images being the same size and the text being the same size, the cells would be the same size and the grid would line up ... but noooo ;)
See here for how it looks now and here for how it looks with relative layout.
Both this and this suggest using a RelativeLayout.
The gridview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:numColumns="auto_fit"
android:gravity="top"
android:layout_gravity="top"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="50dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>
</LinearLayout>
The cell:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="top"
android:gravity="top">
<ImageView
android:id="#+id/icon_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top"
android:layout_gravity="top">
</ImageView>
<TextView
android:id="#+id/icon_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center_horizontal"
android:textColorHighlight="#656565">
</TextView>
<TextView
android:id="#+id/full_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="top" >
</TextView>
</RelativeLayout>
So ... I might have one thing wrong or several, to be sure. But I could use your help.
Thanks.
EDIT: Someone suggested I post my adapter code, so here it is.
First, the gridview activity:
package com.buildingfive.sharealike;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.buildingfive.R;
public class BrowseSearchProducts extends Activity {
GridView gridView;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse_search);
//get gridview data from db
DBHelper db = new DBHelper(this);
//this cursor is never really closed, everywhere I tried, GPF
cursor = db.getReadableDatabase().rawQuery("SELECT _id, Title, Image FROM products;", null);
cursor.moveToFirst();
//populate gridview
gridView = (GridView) findViewById(R.id.gridView);
ListAdapter listAdapter = new ImageAdapter(this, cursor);
((ImageAdapter) listAdapter).setCount(cursor.getCount());
gridView.setAdapter(listAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView vText = (TextView) v.findViewById(R.id.full_text);
String strCaption = ((TextView) vText).getText().toString();
Intent intent = new Intent(BrowseSearchProducts.this, ShowDetails.class);
intent.putExtra("search", strCaption);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
cursor.close();
this.finish();
super.onDestroy();
}
}
Now the custom ImageAdapter:
package com.buildingfive.sharealike;
import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.buildingfive.R;
public class ImageAdapter extends BaseAdapter {
Context mContext;
Cursor mCursor;
int mCount;
public static final int ACTIVITY_CREATE = 10;
public ImageAdapter(Context c, Cursor cursor){
mContext = c;
mCursor = cursor;
}
public void setCount(int nCount) {
this.mCount = nCount;
}
#Override
public int getCount() {
return mCount;
}
//also required
public Object getItem(int position) {
//should return the actual object at the specified position in our Adapter
return mCursor.getString(1);
}
//required
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vwIconPlusCaption;
String strCaption = mCursor.getString(1);
String strFull = strCaption;
if (strCaption == "")
return null;
//The Beckham Experiment: Blah Blah Blah 2ndary Tagline
if (strCaption.indexOf(":") > -1)
strCaption = strCaption.split(":")[0].toString();
else
if (strCaption.length() >= 17)
strCaption = strCaption.substring(0, 17);
if(convertView == null){
LayoutInflater li;
li = LayoutInflater.from(mContext);
//icon_plus_caption is loaded into a view
vwIconPlusCaption = li.inflate(R.layout.icon_plus_caption, null);
TextView tv = (TextView) vwIconPlusCaption.findViewById(R.id.icon_text);
//the view's caption set here
tv.setText(strCaption);
TextView fullText = (TextView) vwIconPlusCaption.findViewById(R.id.full_text);
//passes the full title in a hidden ("gone") textview
fullText.setText(strFull);
ImageView iv = (ImageView) vwIconPlusCaption.findViewById(R.id.icon_image);
byte[] bb = mCursor.getBlob(2);
if (bb == null) {
//image not found
iv.setImageResource(R.drawable.not_found);
} else {
iv.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
if (position + 1 < mCount)
mCursor.moveToNext();
}
else
{
vwIconPlusCaption = convertView;
}
return vwIconPlusCaption;
}
}
EDIT: SOLVED: SOLUTION IS AS FOLLOWS:
For some reason, the sizes differ when pulling all the images from SQL lite VS the "not found" image from android resources. See this link for more info.
The line I added was:
iv.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 115, 115, true));
... in order to force the size of the android drawable to 115 x 115.
Thanks for everyone who tried to pitch in.

Displaying pictures stored on the SD Card using a Gridview

I am relatively new to android and I really need help with this one. I am trying to write some code that will display the pictures on the sd card using a GridView, but so far when I run the application only the textview at the top is shown. I would like to know if there is a serious flaw in the logic of my code in the Main Activity code, Image Adapter class code or both. This is my code:
package com.newtestforsdcarddisplay;
import android.app.Activity;
import android.os.Bundle;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.Toast;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.net.Uri;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
public Cursor myImageCursor;
public int columnNumber;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] imageIDs = new String[]{Thumbnails._ID};
Uri myImagesSource = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
myImageCursor = managedQuery(myImagesSource,
imageIDs, null, null, MediaStore.Images.Thumbnails._ID);
columnNumber = myImageCursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
GridView PhoneImageView = (GridView)findViewById(R.id.sdcard);
PhoneImageView.setAdapter(new ImageAdapter(this));
PhoneImageView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String[] data = { MediaStore.Images.Media.DATA };
Cursor viewImageCursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, data,
null, null, MediaStore.Images.Thumbnails._ID );
int imageColumnIndex = viewImageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
viewImageCursor.moveToPosition(position);
viewImageCursor.moveToFirst();
String filepath = viewImageCursor.getString(imageColumnIndex);
Toast.makeText(MainActivity.this, filepath, Toast.LENGTH_LONG).show();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filepath);
}
});
}
}
package com.newtestforsdcarddisplay;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.net.Uri;
import android.provider.MediaStore;
public class ImageAdapter extends BaseAdapter{
final MainActivity pca = new MainActivity();
private Context context;
public ImageAdapter(Context localContext) {
// context = localContext;
}
public int getCount() {
// return pca.myImageCursor.getCount();
return 0;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
pca.myImageCursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = pca.myImageCursor.getInt(pca.columnNumber);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
package com.newtestforsdcarddisplay;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.net.Uri;
import android.provider.MediaStore;
public class ImageAdapter extends BaseAdapter{
final MainActivity pca = new MainActivity();
private Context context;
public ImageAdapter(Context localContext) {
// context = localContext;
}
public int getCount() {
// return pca.myImageCursor.getCount();
return 0;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
pca.myImageCursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = pca.myImageCursor.getInt(pca.columnNumber);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<GridView
android:id="#+id/sdcard"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</LinearLayout>
Could somebody help me please???? As I said before, I am fairly new to android and I have been struggling with this for a really long time. Any help would VERY MUCH appreciated.
Do you still need help with this question?
What I would do is create a "root" layout like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include layout="#layout/my_header"/>
<include layout="#layout/my_grid"/>
</LinearLayout>
In the my_header.xml, just set your textview in a linear layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
Then in your my_grid.xml, setup your gridview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<GridView
android:id="#+id/sdcard"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</LinearLayout>
Good luck
your getCount() is returning 0. i think you should return myImageCursor.getCount()
you can change constructor to
ImageAdapter(Context ctx,Cursor cr)
{
this.context=ctx;
this.cursor=cr;
}
and then use cr.getCount() in adapter's getCount()

Categories

Resources