How can access all images from sd card in HTC Desire Z - android

I am trying to show all images from SD card HTC desire Z Android Mobile. I use this websites sample code:
But Music Video all are access from SD card.but I am unable to show images. There is no Error,No bugs. Just show black screen. How can I access images?
Any one can have better idea. Can anyone give me some sample code?
By the way this web sites sample code is working fine in another mobile. I test it.
Please provide some positive guide.

This is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter"/>
<TextView android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/imageView"
android:layout_gravity="right|center_vertical"
android:text="Next"
android:textColor="#android:color/white"
android:textSize="30sp"/>
<TextView android:id="#+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="Prev"
android:textColor="#android:color/white"
android:textSize="30sp"/>
</FrameLayout>
This is the java file
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
public class DisplayAllImages extends Activity {
ImageView mImageView;
TextView mNext;
TextView mPrev;
Cursor mCursor;
ArrayList list;
int mIndex = 0;
int mSize;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mImageView = (ImageView)findViewById(R.id.imageView);
mNext = (TextView)findViewById(R.id.next);
mPrev = (TextView)findViewById(R.id.prev);
}
#Override
protected void onResume() {
mCursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[] {Media.DATA}, null, null, null);
if(mCursor!=null && mCursor.moveToFirst()) {
list = new ArrayList();
mSize = mCursor.getCount();
do {
list.add(mCursor.getString(0));
} while(mCursor.moveToNext());
mImageView.setImageURI(Uri.parse(list.get(mIndex)));
}
mNext.bringToFront();
mNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mIndex == (mSize-1)) {
mIndex = -1;
}
mImageView.setImageURI(Uri.parse(list.get(++mIndex)));
}
});
mPrev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mIndex == 0) {
mIndex = mSize;
}
mImageView.setImageURI(Uri.parse(list.get(--mIndex)));
}
});
super.onResume();
}
}

What you can do is:-
Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{android.provider.MediaStore.Images.Media.DATA}, null, null, null);
if(cursor!=null && cursor.moveToFirst()) {
do {
//write your code here to show images in a view
// you can access data through cursor.getString(0)
} while(cursor.moveToNext());
}
Hope that helps

Related

Image Buttons lose images on Orientation Change

i have a few pages realized with a PagerAdapter and one layout-file in the folder "res/layout" and one layout-file in "res/layout-land". Each Layout has two ImageButtons, where:
imageButton1 in portrait has the same ID as the imageButton1 in landscape.
imageButton2 in portrait has the same ID as the imageButton2 in landscape.
I have assigned an onClickListener to imageButton1 button which:
takes the images from the ImageButtons
rescales the Images to fit/fill the ImageButtons
and reassigns the rescaled pictures to the ImageButtons.
But whenever i change the orientation in my emulator the images/pictures in these buttons get lost, or change to the images specified in the layout-file originally and dont refresh to the pictures i assigned to the buttons programmatically.
PS (for example): i assigned in onCreate a listener to button1 and that listener works for this button both in portrait and also in landscape. So these are not seperated buttons!!!!!!
Question: how can i make it work that the images are not lost when changing orientation?
thx for any help in advance!
here is my code:
layout-portrait file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<!-- Row 1-->
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
layout-landscape file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
MyPageAdapter-class:
package com.example.Pagercheck;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MyPageAdapter extends PagerAdapter
{
List<View> pages = null;
public MyPageAdapter(List<View> pages)
{
this.pages = pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public Object instantiateItem(View collection, int position)
{
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view)
{
((ViewPager) collection).removeView((View) view);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void startUpdate(View arg0) {
}
}
My MainActivity-Class:
package com.example.Pagercheck;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private List<View> pages;
private MyPageAdapter pagerAdapter;
private ViewPager viewPager;
private static Context context; //member zum speichern für context für andere Klassen
public static Context getContext(){ return context;} //context für andere Klassen zugänglich machen
//private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
context = this; //context in member speichern
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
pagerAdapter = new MyPageAdapter(pages);
viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
setContentView(viewPager);
for (int i_page=0;i_page<pages.size();i_page++)
{
//Drag-Listener auf ImageButtons:
pages.get(i_page).findViewById(R.id.imageButton1).setOnLongClickListener(new MyLongClickListener());
pages.get(i_page).findViewById(R.id.imageButton1).setOnClickListener(this);
pages.get(i_page).findViewById(R.id.imageButton2).setOnLongClickListener(new MyLongClickListener());
//Drag-Listener auf LinearLayouts:
pages.get(i_page).findViewById(R.id.layout11).setOnDragListener(new MyDragListener());
pages.get(i_page).findViewById(R.id.layout12).setOnDragListener(new MyDragListener());
}
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
//NOTE FOR STACKOVERFLOW
//I COMMENTED THIS OUT SO THAT MY IMAGE BUTTONS DOESNT GET LOST AFTER PAGE 2 SO THAT I CAN TEST MY APP PROPERLY WITH ONCLICK:
// Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
//
// for (int i_page=0;i_page<pages.size();i_page++)
// {
//
// ((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
//
//
// }
}
public void scalePictureToFitButtom(ImageButton img_btn)
{
int width=img_btn.getWidth();
int height=img_btn.getHeight();
BitmapDrawable draw=(BitmapDrawable)img_btn.getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
Bitmap resized = Bitmap.createScaledBitmap(bmp, width-40, height-40, true); //bissle schmaler und niedriger damit man noch den Klickeffekt sieht
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.width=width;
params.height=height;
img_btn.setImageBitmap(resized);
img_btn.setLayoutParams(params);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View view)
{
Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
for (int i_page=0;i_page<pages.size();i_page++)
{
((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
}
Toast einToast = Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT);
einToast.show();
}
}
UPDATE:
i did it like this now (example for saving and restoring Bitmap of imageButton1):
#Override
protected void onSaveInstanceState(Bundle outState)
{
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
BitmapDrawable draw=(BitmapDrawable)((ImageButton)pages.get(0).findViewById(R.id.imageButton1)).getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
outState.putParcelable("IMG_OF_BUTTON1", bmp);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Bitmap bmp= savedInstanceState.getParcelable("IMG_OF_BUTTON1");
((ImageButton)pages.get(0).findViewById(R.id.imageButton1)).setImageBitmap(bmp);
}

listview item click different one

I was adding records to my android sqlite databasr which are shown on my listview, when I click the first ones,they change their color(selected) , which is fine. but when I click the middle ones, the
last ones are marked and when I click the last ones the app "stopped unexpectedly". I guess the problem is that when i click the last ones there three records after that and thats why it jumps, but how can I solve it?
here's the catlog:
08-04 18:13:42.976: E/Database(1316): close() was never explicitly called on database '/data/data/com.example.lamder/databases/REGISTRATION_DB'
08-04 18:13:42.976: E/Database(1316): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
08-04 18:13:42.976: E/Database(1316): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1810)
08-04 18:13:42.976: E/Database(1316): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:817)
08-04 18:13:42.976: E/Database(1316): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:851)
and here's my code
package com.example.lamder;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class GetActivity extends Activity {
RegistrationAdapter adapter_ob;
RegistrationOpenHelper helper_ob;
SQLiteDatabase db_ob;
ListView nameList;
Button registerBtn;
Cursor cursor;
static boolean[] check=new boolean[100];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getact);
nameList = (ListView) findViewById(R.id.lv_name);
registerBtn = (Button) findViewById(R.id.btn_register);
adapter_ob = new RegistrationAdapter(this);
cursor=adapter_ob.queryName();
Context context = getApplicationContext();
CharSequence text = "select questions by clicking on them";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
for(int i=0;i<check.length;i++)
check[i]=false;
String[] from = { helper_ob.FNAME, helper_ob.LNAME };
int[] to = { R.id.tv_fname, R.id.tv_lname };
cursor = adapter_ob.queryName();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.row, cursor, from, to);
nameList.setAdapter(cursorAdapter);
nameList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(check[position]==false)
{
check[position]=true;
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#40FF00"));
}
else
{
check[position]=false;
parent.getChildAt(position).setBackgroundColor(Color.TRANSPARENT);
}
cursor.close();
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ String ques[]=new String[cursor.getCount()];
int i=0;
cursor.moveToFirst();
while(!cursor.isAfterLast() )
{
ques[i]= cursor.getString(cursor.getColumnIndex(helper_ob.FNAME));
i++;
cursor.moveToNext();
}
i=0;
String ans[]=new String[cursor.getCount()];
cursor.moveToFirst();
while(!cursor.isAfterLast() )
{
ans[i]= cursor.getString(cursor.getColumnIndex(helper_ob.LNAME));
i++;
cursor.moveToNext();
}
int counter=0;
for(int t=0;t<check.length;t++)
{
if(check[t]==true)
counter++;
}
String[] ques1=new String[counter];
String[] ans1=new String[counter];
int count=0;
for(int t=0;t<ans.length;t++)
{
if(check[t]==true)
{
ques1[count]=ques[t];
ans1[count]=ans[t];
count++;
}
}
if(counter>0)
{
Intent intent=new Intent(GetActivity.this,ThirdActivity.class);
intent.putExtra("Answer",ans1);
intent.putExtra("Question",ques1);
intent.putExtra("truecount",0);
intent.putExtra("falsecount",0);
startActivity(intent);
}
else
{
Context context = getApplicationContext();
CharSequence text = "select questions by clicking on them";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
#Override
public void onResume()
{
super.onResume();
cursor.requery();
}
}
and xml file:
<?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:background = "#drawable/backnote"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv_name"
android:layout_width="wrap_content"
android:layout_height="337dp"
android:layout_weight="0.63" >
</ListView>
<Button
android:id="#+id/btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start" />
</LinearLayout>
and the row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="75dp" >
<TextView
android:id="#+id/tv_fname"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/imageView1"
android:text="ans" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tv_lname"
android:layout_marginLeft="44dp"
android:layout_toRightOf="#+id/tv_fname" >
</RelativeLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/blackbar" />
<TextView
android:id="#+id/tv_lname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/tv_fname"
android:text="ques" />
</RelativeLayout>
</LinearLayout>
That is a database error. Go to the function where you are querying your data. then before returning the result, close your database.
It is default error of list view in android buddy. if you want to still to do so, you have to make custom list view.
see following link for that
Tutorial for Create custom list view

How to set a TextView from an ArrayList, character by character, sequentially?

I want to put a text in a TextView sequentially, with a known time between characters, from a written text in an EditText
That is the solution I made:
I wrote two ArrayList charged from an EditText, the first one with Characters from the EditText , the second one with Integers for determine the time between characters.
Then I parse the ArrayLists, times load of the time integers are done sequentially, but not the characters, the TextViews are drawn only when the cycle ends.
My code
The MainActivity:
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView showCharacter;
private TextView showAppendCharacter;
private EditText incomingText;
private Button readTextEdit;
private ArrayList<CharSequence> toText = new ArrayList<CharSequence>();
private ArrayList<Integer> timePlay = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showCharacter = (TextView) findViewById(R.id.showCharacterTextView);
showAppendCharacter = (TextView) findViewById(R.id.showAppendCharacterTextView);
incomingText = (EditText) findViewById(R.id.incomingEditText);
readTextEdit = (Button) findViewById(R.id.readTextButton);
readTextEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toText.clear();
timePlay.clear();
showAppendCharacter.setText("");
String text = incomingText.getText().toString();
for (int base = 0; base < text.length(); base++) {
if (String.valueOf(text.charAt(base)).equals("a")) {
toText.add(("a"));
timePlay.add(500);
} else if (String.valueOf(text.charAt(base)).equals("b")) {
toText.add(("b"));
timePlay.add(650);
} else if (String.valueOf(text.charAt(base)).equals("c")) {
toText.add(("c"));
timePlay.add(800);
} else {
toText.add(("_"));
timePlay.add(1000);
}
}
for (int pos = 0; pos < toText.size(); pos++) {
try {
Thread.sleep(timePlay.get(pos));
showCharacter.setText((String) toText.get(pos));
showAppendCharacter.append((String) toText.get(pos));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
The activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/showCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showCharacterTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/showAppendCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showAppendCharactersTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/incomingEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/incomingTextEditText"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/readTextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/readButton" />
The strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">texto Desde ArrayList</string>
<string name="action_settings">Settings</string>
<string name="showCharacterTextView">Show last Character</string>
<string name="showAppendCharactersTextView">Show append Characters</string>
<string name="incomingTextEditText">Incoming text</string>
<string name="readButton">Read text</string>
Try something like this... You can get rid of the Arraylists. Remember a String is basically an array of chars. create a custom text view that implements runnable so the work that your trying to do with the text is not done on the main thread.
package com.example.stackquestion;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomTextView extends TextView implements Runnable {
String text = null;
int i = 0;
int length = 0;
String currentText = "";
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
reset();
}
#Override
public void run() {
if (i < length) {
currentText = currentText + text.charAt(i);
setText(currentText);
if (text.charAt(i) == 'a') {
postDelayed(this, 500);
} else if (text.charAt(i) == 'b') {
postDelayed(this, 650);
} else if (text.charAt(i) == 'c') {
postDelayed(this, 800);
} else if (text.charAt(i) == '_') {
postDelayed(this, 1000);
} else
postDelayed(this, 1);
i++;
}
}
public void setString(String text) {
this.text = text;
this.length = text.length();
}
public void reset() {
currentText = "";
text = null;
i = 0;
setText("");
}
}
Here is the main Activity
package com.example.stackquestion;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView showCharacter;
private CustomTextView showAppendCharacter;
private EditText incomingText;
private Button readTextEdit;
private ArrayList<CharSequence> toText = new ArrayList<CharSequence>();
private ArrayList<Integer> timePlay = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showCharacter = (TextView) findViewById(R.id.showCharacterTextView);
showAppendCharacter = (CustomTextView) findViewById(R.id.showAppendCharacterTextView);
incomingText = (EditText) findViewById(R.id.incomingEditText);
readTextEdit = (Button) findViewById(R.id.readTextButton);
readTextEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.readTextButton)
showAppendCharacter.reset();
showAppendCharacter
.setString(incomingText.getText().toString());
showAppendCharacter.run();
}
});
}
}
woops. I forgot to give you the Layout. But looks like you got it. Just change the type of textview to a fully qualified CustomTextView. Here was mine.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/showCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showCharacterTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<com.example.stackquestion.CustomTextView
android:id="#+id/showAppendCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showAppendCharactersTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/incomingEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/incomingTextEditText"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/readTextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/readButton" />
</LinearLayout>

Achartengine draws extra garbage characters

I like the achartengine charting library for Android, but I keep getting this problem. I want the activity to redraw a chart for different data sets from my db (going back different amounts of time) on a button click. I have three buttons in the activity along with the chart (below the listview that contains the chart). Everything works except some extra garbage characters are drawn behind a button after it is pressed. It doesn't happen on the first press of a button, but on the press of a button (doesn't matter which) the garbage appears.
My Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/chart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#000000"/>
<Button
android:id="#+id/oneMonth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="25dp"
android:text="#string/OneMonth" />
<Button
android:id="#+id/twoMonth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="#string/TwoMonth" />
<Button
android:id="#+id/threeMonth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="25dp"
android:text="#string/ThreeMonth" />
</RelativeLayout>
My activity:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class Plot extends Activity{
/** Called when the activity is first created. */
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
List<double[]> values = new ArrayList<double[]>();
private GraphicalView mChartView;
private TimeSeries time_series;
private final String RANGE = "range";
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.plot);
layout = (LinearLayout)findViewById(R.id.chart);
final Button set30 = (Button)findViewById(R.id.oneMonth);
final Button set60 = (Button)findViewById(R.id.twoMonth);
final Button set90 = (Button)findViewById(R.id.threeMonth);
set30.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
setUpChart(-30);
}});
set60.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
setUpChart(-60);
}});
set90.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
setUpChart(-90);
}});
}
#Override
protected void onResume() {
super.onResume();
setUpChart(-30);
}
private void fillData(int x) {
DataBaseHelper helper = new DataBaseHelper(this.getApplicationContext());
helper.open(DataBaseHelper.READABLE);
Cursor cursor = helper.getDaysSoManyDaysInThePast(x);
if(cursor.getCount() != 0){
DateFormat formatter ;
Date date = null;
formatter = new SimpleDateFormat(DataBaseHelper.DATE_FORMAT);
String s;
int dateCol = cursor.getColumnIndex("date");
int caffCol = cursor.getColumnIndex("sum(mgCaffeine)");
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
s = cursor.getString(dateCol);
try {
date = (Date)formatter.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
int caff = cursor.getInt(caffCol);
time_series.add(date, caff);
}
}else{
Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show();
}
helper.close();
}
private void setUpChart(int x){
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer();
mRenderer.setAxisTitleTextSize(16);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(20);
mRenderer.setPointSize(3f);
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(Color.GREEN);
r.setPointStyle(PointStyle.CIRCLE);
r.setFillPoints(true);
mRenderer.addSeriesRenderer(r);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(20);
mRenderer.setPanEnabled(true);
time_series = new TimeSeries("test");
mDataset.addSeries(time_series);
fillData(x);
mChartView = ChartFactory.getTimeChartView(this, mDataset, mRenderer,
DataBaseHelper.DATE_FORMAT);
layout.removeAllViews();
layout.addView(mChartView);
}
}
Here's a picture The garbage is behind the bottom part of the button. Any help would be appreciated.
I found a way to fix it --- enclose the buttons in a relativelayout and give the linealayout that has the chart a bottom margin of 50dp.
You can try to do the following call.
mRenderer.setInScroll(true);

Android: ListView with CheckBox, populated from SQLite database not quite working

As with several other posts here, I am trying to create a ListView that includes a CheckBox for each row, and use a SQLite database to store the current state of the selection.
Starting with the example at http://appfulcrum.com/?p=351, which did not quite work as is, I created a simple app that creates the database, populates it with 20 items, and displays the list.
It successfully retrieves the state and stores the state of the selection.
BUT, it does not correctly show the CheckBox state if I change it, scroll to the other end of the list, and scroll back. e.g. if I select the first CheckBox, scroll to the bottom, and come back to the top, the CheckBox is no longer set. This is being run on an Android 2.1 Samsung handset.
If I return to the main screen, come back into the list, the CheckBox is correctly set, so the database has indeed been updated.
The example extends SimpleCursorAdapter, and the getView() invokes setChecked() with true or false as appropriate based on the value of the selection column in the table.
Below are all the sources.
I'd certainly appreciate being told, "Duh, here's your problem..."
CustomListViewDB.java
// src/CustomListViewDB.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class CustomListViewDB extends ListActivity {
private ListView mainListView = null;
CustomSqlCursorAdapter adapter = null;
private SqlHelper dbHelper = null;
private Cursor currentCursor = null;
private ListView listView = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
if (this.dbHelper == null) {
this.dbHelper = new SqlHelper(this);
}
listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//listView.setClickable(true);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearDBSelections();
}
});
new SelectDataTask().execute();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
}
#Override
protected void onRestart() {
super.onRestart();
new SelectDataTask().execute();
}
#Override
protected void onPause() {
super.onPause();
this.dbHelper.close();
}
protected void ClearDBSelections() {
this.adapter.ClearSelections();
}
private class SelectDataTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
try {
CustomListViewDB.this.dbHelper.createDatabase(dbHelper.dbSqlite);
CustomListViewDB.this.dbHelper.openDataBase();
CustomListViewDB.this.currentCursor = CustomListViewDB.this.dbHelper
.getCursor();
} catch (SQLException sqle) {
throw sqle;
}
return null;
}
// can use UI thread here
protected void onPostExecute(final String result) {
startManagingCursor(CustomListViewDB.this.currentCursor);
int[] listFields = new int[] { R.id.txtTitle };
String[] dbColumns = new String[] { SqlHelper.COLUMN_TITLE };
CustomListViewDB.this.adapter = new CustomSqlCursorAdapter(
CustomListViewDB.this, R.layout.single_item,
CustomListViewDB.this.currentCursor, dbColumns, listFields,
CustomListViewDB.this.dbHelper);
setListAdapter(CustomListViewDB.this.adapter);
}
}
}
CustomSqlCursorAdapter.java
// src/CustomSqlCursorAdapter.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class CustomSqlCursorAdapter extends SimpleCursorAdapter {
private Context mContext;
private SqlHelper mDbHelper;
private Cursor mCurrentCursor;
public CustomSqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, SqlHelper dbHelper) {
super(context, layout, c, from, to);
this.mCurrentCursor = c;
this.mContext = context;
this.mDbHelper = dbHelper;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.single_item, null);
}
if (!this.mCurrentCursor.moveToPosition(pos)) {
throw new SQLException("CustomSqlCursorAdapter.getView: Unable to move to position: "+pos);
}
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
// save the row's _id value in the checkbox's tag for retrieval later
cBox.setTag(Integer.valueOf(this.mCurrentCursor.getInt(0)));
if (this.mCurrentCursor.getInt(SqlHelper.COLUMN_SELECTED_idx) != 0) {
cBox.setChecked(true);
Log.w("SqlHelper", "CheckBox true for pos "+pos+", id="+this.mCurrentCursor.getInt(0));
} else {
cBox.setChecked(false);
Log.w("SqlHelper", "CheckBox false for pos "+pos+", id="+this.mCurrentCursor.getInt(0));
}
//cBox.setOnClickListener(this);
cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.w("SqlHelper", "Selected a CheckBox and in onCheckedChanged: "+isChecked);
Integer _id = (Integer) buttonView.getTag();
ContentValues values = new ContentValues();
values.put(SqlHelper.COLUMN_SELECTED,
isChecked ? Integer.valueOf(1) : Integer.valueOf(0));
mDbHelper.dbSqlite.beginTransaction();
try {
if (mDbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
new String[] { Integer.toString(_id) }) != 1) {
throw new SQLException("onCheckedChanged failed to update _id="+_id);
}
mDbHelper.dbSqlite.setTransactionSuccessful();
} finally {
mDbHelper.dbSqlite.endTransaction();
}
Log.w("SqlHelper", "-- _id="+_id+", isChecked="+isChecked);
}
});
TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.mCurrentCursor.getString(this.mCurrentCursor
.getColumnIndex(SqlHelper.COLUMN_TITLE)));
return (v);
}
public void ClearSelections() {
this.mDbHelper.clearSelections();
this.mCurrentCursor.requery();
}
}
ListViewWithDBActivity.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.Activity;
import android.os.Bundle;
public class ListViewWithDBActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
SqlHelper
// SqlHelper.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class SqlHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = "/data/data/com.appfulcrum.blog.examples.listviewcustomdb/databases/";
public static final String DATABASE_NAME = "TODOList";
public static final String TABLE_NAME = "ToDoItems";
public static final int ToDoItems_VERSION = 1;
public static final String COLUMN_ID = "_id"; // 0
public static final String COLUMN_TITLE = "title"; // 1
public static final String COLUMN_NAME_DESC = "description";// 2
public static final String COLUMN_SELECTED = "selected"; // 3
public static final int COLUMN_SELECTED_idx = 3;
public SQLiteDatabase dbSqlite;
private Context mContext;
public SqlHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
createDB(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("SqlHelper", "Upgrading database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS ToDoItems;");
createDB(db);
}
public void createDatabase(SQLiteDatabase db) {
createDB(db);
}
private void createDB(SQLiteDatabase db) {
if (db == null) {
db = mContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
db.execSQL("CREATE TABLE IF NOT EXISTS ToDoItems (_id INTEGER PRIMARY KEY, title TEXT, "
+" description TEXT, selected INTEGER);");
db.setVersion(ToDoItems_VERSION);
//
// Generate a few rows for an example
//
// find out how many rows already exist, and make sure there's some minimum
SQLiteStatement s = db.compileStatement("select count(*) from ToDoItems;");
long count = s.simpleQueryForLong();
for (int i = 0; i < 20-count; i++) {
db.execSQL("INSERT INTO ToDoItems VALUES(NULL,'Task #"+i+"','Description #"+i+"',0);");
}
}
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (dbSqlite != null)
dbSqlite.close();
super.close();
}
public Cursor getCursor() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_TITLE,
COLUMN_NAME_DESC, COLUMN_SELECTED };
Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
null, null, null, COLUMN_ID+" ASC");
return mCursor;
}
public void clearSelections() {
ContentValues values = new ContentValues();
values.put(COLUMN_SELECTED, 0);
this.dbSqlite.update(SqlHelper.TABLE_NAME, values, null, null);
}
}
Start.java
//src/Start.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Start extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSimple = (Button) findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked ListView From DB button", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), CustomListViewDB.class);
startActivityForResult(intent, 0);
}
});
}
}
layout/main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/buttonlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="left|top" android:paddingTop="2dp"
android:paddingBottom="2dp">
<TextView android:id="#+id/txtTest" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textStyle="bold"
android:text="#string/app_name" android:textSize="15sp"
android:textColor="#FF0000" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
<Button android:id="#+id/btnSimple"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Listview from DB"
android:textColor="#000000"
>
</Button>
</LinearLayout>
layout/simple.xml
<?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">
<LinearLayout android:id="#+id/buttonlayout"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:height="32dp"
android:gravity="left|top" android:paddingTop="2dp"
android:paddingBottom="2dp">
<LinearLayout android:id="#+id/buttonlayout2"
android:orientation="horizontal" android:layout_height="wrap_content"
android:gravity="left|center_vertical" android:layout_width="wrap_content"
android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/txtTest"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:text="#string/list_header" android:textSize="15sp"
android:gravity="center_vertical" android:paddingLeft="5dp">
</TextView>
<Button android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear"
android:textSize="15sp" android:layout_marginLeft="10px"
android:layout_marginRight="10px"
android:layout_marginBottom="2px"
android:layout_marginTop="2px" android:height="15dp"
android:width="70dp"></Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:stretchColumns="*">
<TableRow>
<ListView android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</TableRow>
</TableLayout>
</LinearLayout>
layout/single_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="wrap_content"
android:orientation="horizontal" android:gravity="center_vertical">
<CheckBox android:id="#+id/bcheck"
android:layout_width="wrap_content"
android:layout_height="fill_parent" />
<TextView android:id="#+id/txtTitle"
android:layout_width="wrap_content" android:gravity="left|center_vertical"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_alignParentLeft="true"
android:textSize="20sp" android:text="Test"
android:textStyle="bold" android:paddingLeft="5dp"
android:paddingRight="2dp" android:focusable="false"
android:focusableInTouchMode="false"></TextView>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal"
android:gravity="right|center_vertical">
</LinearLayout>
</LinearLayout>
values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ListViewWithDBActivity!</string>
<string name="app_name">ListViewWithDB</string>
<string name="list_header">List Headers</string>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1" android:versionName="1.0"
package="com.appfulcrum.blog.examples.listviewcustomdb">
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar">
>
<activity android:name=".Start" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CustomListViewDB"></activity>
</application>
<uses-sdk android:minSdkVersion="7" /> <!-- android 1.6 -->
</manifest>
If you want to build, throw some arbitrary icon.png into drawable.
Thanks in advance.
I found the most complete solution to the problem off-site.
At Android ListView with CheckBox : Retain State
Appreciate the help folks.
The Views in a ListView are recycled, and this sounds like an issue with that. You probably need to invalidate your onCheckedChangedListener so that when you do setChecked() it isn't calling the previous listener inadvertently. There could be other ramifications of the recycling as well, so keep that in mind.
So try:
cBox.setOnCheckedChangeListener(null);
...
cBox.setChecked();
...
cBox.setOnCheckedChangeListner(<real listener);

Categories

Resources