Android: only some rows are displayed at first run - android

The Listview is displaying some rows instead of all items (sometimes, it's displaying nothing), I couldn't understand why this is happenning. It occurs at first run. After that, it works well, with all items from database filled on the screen. I put vertical orientation in my linear layout xml files and wrap_content height. But the problem is not solved.
This is my main activity :
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile1";
private TextView mTextView;
private ListView mListView;
ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();
DictionaryDatabase DictionaryDatabase;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text);
mListView = (ListView) findViewById(R.id.list);
DictionaryDatabase=new DictionaryDatabase(this);
allWordDefinitions=DictionaryDatabase.getAllWords();
Collections.sort(allWordDefinitions, new CustomComparator());
mListView.setAdapter(new BaseAdapter() {
#Override
public View getView(int position, View view, ViewGroup arg2) {
if (view==null) {
view=getLayoutInflater().inflate(R.layout.list_item, arg2, false);
}
TextView textView=(TextView) view.findViewById(R.id.listItemTextView);
textView.setText(allWordDefinitions.get(position).word);
return view;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return allWordDefinitions.size();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Intent intent =new Intent(MainActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", allWordDefinitions.get(position).word);
intent.putExtra("definition", allWordDefinitions.get(position).definition);
startActivity(intent);
}
});
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, WordActivity.class);
this.finish();
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
mTextView.setText(getString(R.string.no_results, new Object[] {query}));
} else {
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
mTextView.setText(countString);
String[] from = new String[] { DictionaryDatabase.KEY_WORD,
DictionaryDatabase.KEY_DEFINITION };
int[] to = new int[] { R.id.word,
R.id.definition };
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.result, cursor, from, to);
mListView.setAdapter(words);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI,
String.valueOf(id));
wordIntent.setData(data);
startActivity(wordIntent);
}
});
}
}
public class CustomComparator implements Comparator<WordDefinition> {
#Override
public int compare(WordDefinition p1, WordDefinition p2) {
return p1.word.compareTo(p2.word);
}
}
}
WorDefinition (Array List):
public class WordDefinition {
String word,definition;
public WordDefinition(String word,ArrayList<String> alldefinition) {
this.word=word;
StringBuilder stringBuilder=new StringBuilder();
for (String string : alldefinition) {
stringBuilder.append(string);
}
this.word=stringBuilder.toString();
}
public WordDefinition(String word,String alldefinition) {
this.word=word;
this.definition=alldefinition;
}
}
DictionaryDatabase (snippet)
public ArrayList<WordDefinition> getAllWords() {
ArrayList<WordDefinition> arrayList=new ArrayList<WordDefinition>();
SQLiteDatabase database=mDatabaseOpenHelper.getReadableDatabase();
String selectAllQueryString="SELECT * FROM "+FTS_VIRTUAL_TABLE;
Cursor cursor=database.rawQuery(selectAllQueryString, null);
if (cursor.moveToFirst()) {
do {
WordDefinition wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(KEY_WORD)), cursor.getString(cursor.getColumnIndex(KEY_DEFINITION)));
arrayList.add(wordDefinition);
} while (cursor.moveToNext());
}
return arrayList;
}
Main XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fundoeua"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<LinearLayout
android:id="#+id/Line1"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:textColor="#FFFFFF"
android:gravity="right"
android:textAlignment="gravity"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="15dp"
android:textStyle="bold"
android:textSize="20sp"
android:text="#string/chamada"
android:background="#color/vermelho"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#ff0000"
android:dividerHeight="4px"
/>
</LinearLayout>
</RelativeLayout>
list_item.xml
<?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"
android:background="#drawable/seletor2"
android:orientation="vertical" >
<TextView
android:id="#+id/listItemTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:textColor="#color/preto"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

Sometimes height ListView calculate incorrect.
Android: wrap_content is not working with ListView
You can use one adapter and one ListView instead of Two ListViews. Use types for items in this adapter. In this way you can remove wrap_content and set match_parent for height attribute in ListView

Related

how to call another activity on clicking a listview

Listing all the songs read form external storage. On clicking a song it should go to SecondActivity.java
MainActivity.java
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.example.shubham.hymnattune";
private List peers = new ArrayList();
private MainActivity.MediaCursorAdapter mediaAdapter = null;
private String currentFile = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra(EXTRA_MESSAGE,currentFile);
startActivity(intent);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long duratioInMs = Long.parseLong(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) duratioInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
};
Receive the song selected in MainActivity.java and play it.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
//private MainActivity.MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekBar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
// private final IntentFilter intentFilter = new IntentFilter();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
selectedFile = (TextView) (findViewById(R.id.selectedfile));
seekBar = (SeekBar) (findViewById(R.id.seekbar));
playButton = (ImageButton) (findViewById(R.id.play));
prevButton = (ImageButton) (findViewById(R.id.prev));
nextButton = (ImageButton) (findViewById(R.id.next));
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekBar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
playButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
}
Intent intent=getIntent();
currentFile=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
startPlay(currentFile);
}
This is my main layout file. containing a list of songs from external storage.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.shubham.hymnattune.MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"/>
</LinearLayout>
This is my xml file of second activity which is used for playing a song.
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.shubham.hymnattune.SecondActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:background="#android:drawable/screen_background_light"
android:id="#+id/linear2"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/selectedfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="middle"
android:gravity="center_horizontal"
android:singleLine="true"
android:text="No File Selected"
android:textColor="#android:color/black" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
try this
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.onItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Intent intent=new Intent(this,SecondActivity.class);
startActivity(intent);
}
});
I have used a code inside my adaptor class to implement on item click.. Check this code
public class LazyAdapter extends BaseAdapter {
private VideoActivity mainactivity;
private String[] result,imageId,title;
private static LayoutInflater inflater=null;
Context context;
public LazyAdapter(VideoActivity mainactivity, String[] videourls, String[] imgurls, String [] explist) {
context = mainactivity;
result = videourls;
imageId=imgurls;
title = explist;
inflater = (LayoutInflater)mainactivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(mainactivity.getApplicationContext());
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.listview, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
Glide.with(context)
.load(imageId[position])
.into(holder.img);
holder.tv.setText(title[position]);
// imageLoader.DisplayImage(result[position], holder.img);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+title[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, VideoActivity2.class);
intent.putExtra("imgid",title[position]);
intent.putExtra("videourl",result[position]);
context.startActivity(intent);
}
});
return rowView;
}
}
In this code I also have added a code to pass data on clicking each item in the list view.. Hope this one helps you

How to use onItemclick on a list view parsed from json

I have an app which uses listview to show data received from a JSON.Now, I want an onItemclick listener in the listview so that, after displaying the listview users can click on any row to start a new activity. But the onclicklistener is not working.I am a new developer so am unable to make it work. Kindly help me so that I can implement the onclick Listener. Thanks in advance.
Edited:- Another problem I am facing is that switch case doesnt seem to work because I don't know how many ids will be added to the rows i.e the rows are unknown to me, it may be anything. So what should I use instead of switch case?
Thanks in advance
This is my StatementsActivity.java which displays the listview
public class StatementsActivity extends AppCompatActivity {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
String token = myPrefs.getString("GCMTOKEN", "");
String JSON_URL = "http://xyz.in/view_json.php?device_id=" + token;
private ListView listView;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statements);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_layout, ParseJSON.ids);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent newActivity = new Intent(StatementsActivity.this, MainActivity.class);
startActivity(newActivity);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
sendRequest();
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void sendRequest() {
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(StatementsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
listView.setAdapter(cl);
}
}
This is my CustomList.java class
public class CustomList extends ArrayAdapter<String> {
private String[] ids;
private String[] mem_codes;
private String[] created_ons;
private Activity context;
public CustomList(Activity context, String[] ids, String[] mem_codes, String[] created_ons) {
super(context, R.layout.list_view_layout, ids);
this.context = context;
this.ids = ids;
this.mem_codes = mem_codes;
this.created_ons = created_ons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewMemCode = (TextView) listViewItem.findViewById(R.id.textViewMem_code);
TextView textViewCreatedOn = (TextView) listViewItem.findViewById(R.id.textViewCreated_on);
textViewId.setText(ids[position]);
textViewMemCode.setText(mem_codes[position]);
textViewCreatedOn.setText(created_ons[position]);
return listViewItem;
}
}
And this is my ParseJSON.java class
public class ParseJSON {
public static String[] ids;
public static String[] mem_codes;
public static String[] created_ons;
public static final String KEY_ID = "id";
public static final String KEY_MEM_CODE = "mem_code";
public static final String KEY_CREATED_ON = "created_on";
public static final String JSON_ARRAY = "result";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
mem_codes = new String[users.length()];
created_ons = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
mem_codes[i] = jo.getString(KEY_MEM_CODE);
created_ons[i] = jo.getString(KEY_CREATED_ON);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my activity_statements.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/buttonColor" tools:context=".StatementsActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/toolbar_layout"/>
</LinearLayout>
</RelativeLayout>
And this is my list_view_layout.xml
<?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="wrap_content"
android:background="#color/buttonColor">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewId"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewMem_code"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewCreated_on"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
I have built an android application which displays in Listview style and on clicking on them, shows their respective cost.
Below is the code of that. Hope, it helps you...
public class ListViewActivity extends AppCompatActivity {
private static ListView lv;
private static String[] prod_names = new String[] {"E", "G", "E2", "G2", "X"};
private static int[] cost = new int[] {6500, 13000, 7500, 16000, 25000};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Listener();
}
public void Listener(){
lv = (ListView)findViewById(R.id.listView);
ArrayAdapter <String> adp = new ArrayAdapter<String>(this, R.layout.products_list, prod_names);
lv.setAdapter(adp);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String val = (String)lv.getItemAtPosition(position);
Toast.makeText(ListViewActivity.this, " Release# : "+ (position+1)+"\n Model : "+val+"\n Cost : Rs "+cost[position], Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_view, 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);
}
}
Do it like this in your onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(StatementsActivity.this, MainActivity.class);
// Adding your variable to intent
newActivity.putExtra("position",position);
startActivity(newActivity);
break;
}
});
In your MainActivity.java :
public class MainActivity extends Activity
{
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Receiving your variable in another activity
position = getIntent().getIntExtra("position",0);
}
}
And kindly refer this : How do I pass data between Activities in Android application?
Edit :
Check this out
OnItemCLickListener not working in listview
ListView OnItemClickListener Not Responding?
OnItemClickListener and OnClickListener not working for ListView
ListView.onItemClick not working
Listview itemclick not work

how to add button in custom row listview i want to delete database selected entry in listview

xml for save database please help me to## i want add delete button in listview's each row when button is pressed delete that data from listview and database ##
here is first xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:orientation="vertical"
android:padding="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/frst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First name"
android:textColor="#000" />
<EditText
android:id="#+id/frst_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/frst_txtV" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/lst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Last name"
android:textColor="#000" />
<EditText
android:id="#+id/last_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/lst_txtV" />
</LinearLayout>
<Button
android:id="#+id/save_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Save"
android:textColor="#000" />
</LinearLayout>
display_activty.xml list view xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B58897"
android:gravity="center_horizontal" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Add" />
<View
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/btnAdd"
android:background="#8DB3E1" />
<ListView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/a"
android:divider="#8DB3E1"
android:dividerHeight="2dp" />
</RelativeLayout>
displayadapter.java here i add button if i press button than record is will delete from database as well from listview
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private SQLiteDatabase dataBase;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.btn = (Button) child.findViewById(R.id.Button1);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
}
});
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
Button btn;
//ImageView img;
}
}
listcell.xml this is to display custom listview xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >
<TextView
android:id="#+id/txt_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
<TextView
android:id="#+id/txt_fName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<TextView
android:id="#+id/txt_lName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<Button android:text="Button"
android:id="#+id/Button1"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
DisplayActivty.java here is listview adding class
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Addactivty.java add database class
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
edit_first.setText(fname);
edit_last.setText(lname);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
Create Custom Array Adapter like this
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.inflatelistview, null);
TextView text=(TextView)vi.findViewById(R.id.textView1);
ImageView image=(ImageView)vi.findViewById(R.id.imageView1);
Button btn=(Button)vi.findViewById(R.id.button1);
btn.setTag(position);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
//items.remove(index.intValue());
data.remove(position);
notifyDataSetChanged();
}
});
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
As you're inserting (Addactivty.java add database class) and fetching (DisplayActivty.java here is listview adding class) data from database similarly you can delete.
For example :
public static boolean Delete(Context context, int id) {
SQLiteDatabase db = new MyDataBase(context).getWritableDatabase();
int res = db.delete(CATEGORY, ID + " = " + id, null);
if (db.isOpen())
db.close();
return (res == 0 ? false : true);
}
You need to delete data from database and listView inside the click listener,like :
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//1. get the clicked item's *ID*
// (as you did id.get(pos), in your adapter class).
//2. delete data from database using this *ID*.
// (see above function).
//3. remove position from your list.
// list.remove(position);
// (in your case you've multiple lists remove position from all)
//4. notifyDataSetChanged();
}
});
Helping link :
notifyDataSetChanged();
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

Failing to populate a ListView with an AsyncTask

Trying to get this working... it loads up fine, even tells the application that it completed getting all the data. It does not populate the listview though.
The data response inside mArrayList.toString(): [A, B, C, D]
public class MainActivity extends ActionBarActivity {
private static final String DEBUG_TAG = "MainActivity";
private boolean mAlternateTitle = false;
ListView lv;
private ArrayList<Show> mArrayList;
ShowsAdapter adapter;
AlertDialog mAlertDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mArrayList = new ArrayList<Show>();
lv = (ListView) findViewById(R.id.list);
adapter = new ShowsAdapter(MainActivity.this, android.R.layout.simple_list_item_1, mArrayList);
ShowsList show_list = new ShowsList();
show_list.execute();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
}
private class ShowsList extends AsyncTask<Void, Void, List<Show>> {
#Override
protected void onPreExecute() {
mAlertDialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_action_refresh).setTitle(R.string.fetching_new).show();
}
#Override
protected List<Show> doInBackground(Void... voids) {
final String DEBUG_TAG = "MainActivity$ShowList$doInBackground";
try {
for (Show show : Show.getShows()) {
Log.d(DEBUG_TAG, show.toString());
mArrayList.add(show);
};
return mArrayList;
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this.getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
return null;
}
}
#Override
protected void onPostExecute(final List<Show> show_list) {
if (mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
adapter.notifyDataSetChanged();
}
}
private class ListClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Show show = mArrayList.get(i);
Toast.makeText(MainActivity.this, "Clicked on a list item: " + show.title, Toast.LENGTH_LONG).show();
}
}
private class ShowsAdapter extends ArrayAdapter<Show> {
final String DEBUG_TAG = "MainActivity$ShowsAdapter";
public ShowsAdapter(Context context, int textViewResourceId, List<Show> shows) {
super(context, textViewResourceId, shows);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Show show = this.getItem(position);
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row_show, parent, false);
}
((TextView) convertView.findViewById(R.id.show_title)).setText(show.title);
//Log.d(DEBUG_TAG, (String)((TextView) convertView.findViewById(R.id.show_title)).getText());
//((TextView) convertView.findViewById(R.id.episode_number)).setText(episode.getGrayLine());
return convertView;
}
}
Just in case it could be an issue with the layout [main.xml]:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</FrameLayout>
list_show_row.xml:
<?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">
<TextView
android:textSize="17.0dip"
android:textStyle="bold"
android:textColor="#ff000000"
android:gravity="center_vertical"
android:id="#+id/show_title"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:text="Show Title"
android:layout_weight="1.0"
/>
<TextView
android:textStyle="italic" android:textColor="#ff666666"
android:id="#+id/episode_number"
android:layout_width="fill_parent" android:layout_height="0.0dip" android:text="Episode Number" android:layout_weight="1.0" />
</LinearLayout>
Don't set fill_parent on the layout_height of the root element of list_row_show.xml layout.

Android GridView Item Order Change when Admob displays

I searched for these issues and tried most of the given answers but my issue is not solved yet.
My Grid view has around 10-12 items and and each item has a ImageView and a TextView. image and the texts are dynamically loading from resources.
Issue 1 : When the grid is scrolling the item order changes. first items goes to down and the last items coming to top
Issue 2: When an Admob ad loads in the bottom of the screen entire Grid items are mixing up.Even without any scrolling.
Issue 3: Currently I have put the onClickListeners to the ImageView Only. How do I add the same OnclickListener to the relevant TextView as well
I have used a common gridview generation code found every where in the net.
Here is my code
public class ImageAdapter extends BaseAdapter{
Context myContext;
public ImageAdapter(Context _myContext){
myContext = _myContext;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View MyView = convertView;
try{
if ( convertView == null ){
LayoutInflater li = ((Activity)myContext).getLayoutInflater();
MyView = li.inflate(R.layout.weather_grid, null);
TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text);
Resources res = getResources();
String[] items = res.getStringArray(R.array.weather_items);
final String[] titles = new String[items.length];
int x = 0;
for(String item:items){
titles[x]=item;
x++;
}
// getStringFromRes(titles[position]);
tv.setText(titles[position]);
// Add The Image!!!
final ImageView iv = (ImageView)MyView.findViewById(R.id.grid_item_image);
Class<drawable> resources = R.drawable.class;
Field[] fields = resources.getFields();
String[] imageName = new String[fields.length];
int index = 0;
for( Field field : fields )
{
if(field.getName().startsWith("weather")){
imageName[index] = field.getName();
index++;
}
}
iv.setImageResource(getDrawable(myContext, imageName[position]));
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Clicked Item = " + titles[position]);
Bundle b = new Bundle();
if(titles[position].equals("Weather Overview")){
startActivity(new Intent(WeatherGridActivity.this, WeatherActivity.class));
}
if(titles[position].equals("Current Weather")){
b.putString("display", "current");
Intent intent = new Intent(WeatherGridActivity.this,WeatherActivity.class);
intent.putExtras(b);
startActivityForResult(intent, 0);
//startActivity(new Intent(WeatherGridActivity.this, WeatherActivity.class));
}
if(titles[position].equals("Ask a Question")){
startActivity(new Intent(WeatherGridActivity.this, AskQuestionActivity.class));
}
if(titles[position].equals("Average Temperature")){
startActivity(new Intent(WeatherGridActivity.this, AverageTemperatureActivity.class));
}
}
});
}
}catch(Exception e){
System.out.println("Error Occured = " + e.getMessage());
e.printStackTrace();
}
return MyView;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCount() {
return 10;
}
public int getDrawable(Context context, String name){
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}
public String getStringFromRes(String name){
try{
int resId = (Integer) R.string.class.getField(name).get(null);
// Toast.makeText(MyContext, getResources().getString(resId), Toast.LENGTH_LONG).show();
return getResources().getString(resId);
}catch(Exception e){
// no such string
return "empty";
}
}
}
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg"
android:orientation="vertical" >
<GridView
android:id="#+id/weather"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:columnWidth="70dp"
android:gravity="center_horizontal"
android:horizontalSpacing="20dp"
android:numColumns="auto_fit"
android:padding="20dp"
android:stretchMode="columnWidth"
android:tileMode="repeat"
android:verticalSpacing="20dp" >
</GridView>
<ImageView
android:id="#+id/back_button"
style="#style/book_button" />
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="dummy id"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
</LinearLayout>
</ScrollView>
I have added the RelativeLayout instead of LinerLayout and ScrollViews but now the entire Grid doesn't display but the ads displaying properly.
Here is the new xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/home_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg"
>
<GridView
android:id="#+id/home_grid"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:columnWidth="100dp"
android:rowHeight="30dp"
android:gravity="center_horizontal"
android:horizontalSpacing="5dp"
android:numColumns="auto_fit"
android:stretchMode="none"
android:tileMode="repeat"
android:verticalSpacing="30dp"
>
</GridView>
<com.google.ads.AdView
android:layout_alignParentBottom="true"
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="dummy id"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Your answers are highly appreciated
Thanks
Here is the working code. This fix the scrolling issue,the Admob issue and the onClickListener issue as well.
public class ImageAdapter extends BaseAdapter{
Context myContext;
public ImageAdapter(Context _myContext){
myContext = _myContext;
layoutInflater = LayoutInflater.from(myContext);
Resources res = getResources();
String[] items = res.getStringArray(R.array.weather_items);
titles = new String[items.length];
int x = 0;
for(String item:items){
titles[x]=item;
x++;
}
Class<drawable> resources = R.drawable.class;
Field[] fields = resources.getFields();
imageName = new String[fields.length];
int index = 0;
for( Field field : fields ){
if(field.getName().startsWith("weather")){
imageName[index] = field.getName();
index++;
}
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// View MyView = convertView;
View grid = null;
try{
if ( convertView == null ){
grid = new View(myContext);
// LayoutInflater li = ((Activity)myContext).getLayoutInflater();
grid = layoutInflater.inflate(R.layout.weather_grid, null);
}else{
grid = (View)convertView;
}
TextView tv = (TextView)grid.findViewById(R.id.grid_item_text);
tv.setText(titles[position]);
ImageView iv = (ImageView)grid.findViewById(R.id.grid_item_image);
iv.setImageResource(getDrawable(myContext, imageName[position]));
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
executeListners(position);
}
});
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
executeListners(position);
}
});
}catch(Exception e){
System.out.println("Error Occured = " + e.getMessage());
e.printStackTrace();
}
return grid;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCount() {
return 10;
}
public int getDrawable(Context context, String name){
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}
public String getStringFromRes(String name){
try{
int resId = (Integer) R.string.class.getField(name).get(null);
// Toast.makeText(MyContext, getResources().getString(resId), Toast.LENGTH_LONG).show();
return getResources().getString(resId);
}catch(Exception e){
return "empty";
}
}
}
The xml files has no changes. This works with either RelativeLayout or with a LinearLayout

Categories

Resources