In LoginActivity showing single button
And want to launch UploadActivity, if UploadActivity's List contain any data else show alert "No Images found in UploadActivity"
In short,
i just want to show alert dialog if upload activity has no data in a List else Launch UploadActivity...
btnCheckUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertdialog = new AlertDialog.Builder(LoginActivity.this);
alertdialog.setTitle(getResources().getString(R.string.app_name));
alertdialog.setMessage("No Images found in UploadActivity");
alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertdialog.show();
}
}
});
UploadActivity.java:-
public class UploadActivity extends Activity {
final private static int DIALOG_LOGIN = 1;
EditText editPersonName, editPersonaEmail, editPersonTelephone, parental_email ;
TextView editImageName ;
String fileName;
static ListView lstView;
private Handler handler = new Handler();;
static List <String> ImageList;
String strPath;
CheckBox chkOption3;
TextView tv1, tv2;
CheckBox chkOption1, chkOption2 ;
int position ;
static File f1;
static String folder = null ;
Intent i;
Intent intent ;
TextView textHeading1;
static File[] files;
static File file ;
static List <String> it ;
static String textHeading = null;
// new Class DB
final myDBClasss myDb = new myDBClasss(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
textHeading1 = (TextView) findViewById(R.id.txtEventNameDate1);
textHeading1.setText(CameraLauncherActivity.folder);
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
public static List <String> getSD()
{
it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/Awesome/";
f1 = new File (string+ CameraLauncherActivity.folder+ "/");
files = f1.listFiles ();
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_upload, null);
}
// ColImgName
TextView txtName = (TextView) convertView.findViewById(R.id.ColImgName);
strPath = ImageList.get(position).toString();
// Get File Name
fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length() );
file = new File(strPath);
#SuppressWarnings("unused")
long length = file.length();
txtName.setText(fileName);
// Image Resource
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(strPath,options);
imageView.setImageBitmap(bm);
// ColStatus
final ImageView txtStatus = (ImageView) convertView.findViewById(R.id.ColStatus);
txtStatus.setImageResource(R.drawable.bullet_button);
// progressBar
final ProgressBar progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
//btnUpload
final ImageButton btnUpload = (ImageButton) convertView.findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
btnUpload.setEnabled(false);
startUpload(position);
}
});
return convertView;
}
}
lstView.getChildCount() will Returns the number of children in the group.that is you view.so store the refrence of your ImageAdapter
and then use adapter.getcount();
you can also check for your ImageList size as well.
instead of
if (UploadActivity.lstView.getChildCount() > 0)
use
if (imageList.size) > 0)
or
if (adapter.getcount() > 0)
ListView is a View, calling listView.getChildCount() means :
<ListView>
<TextView></TextView>
</ListView>
It doesn't make sense because a ListView have no child. What you need to Do is call your Adapter.getCount();
If you created your Adapter well it should work just fine.
Make your getSD() as public static and trying to access it in your LogincActivity as below:
btnCheckUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<String> dt=new ArrayList<String>();
dt=UploadActivity.getSD();
if (dt.size()> 0) {
Intent intentUpload = new Intent(LoginActivity.this, UploadActivity.class);
startActivity(intentUpload);
} else {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(LoginActivity.this);
alertdialog.setTitle(getResources().getString(R.string.app_name));
alertdialog.setMessage("No Images found in UploadActivity");
alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertdialog.show();
}
}
});
EDITED:
Another way is check the condition in your UploadActivity only and if no data found then simply show alert and onclick of alert finish the activity as below:
ImageAdapter adapter=new ImageAdapter(this);
if(adapter.getCount()>0)
{
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
else
{
AlertDialog.Builder alertdialog = new AlertDialog.Builder(LoginActivity.this);
alertdialog.setTitle(getResources().getString(R.string.app_name));
alertdialog.setMessage("No Images found in UploadActivity");
alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
finish(); //Finish your UploadActivity here.
}
});
alertdialog.show();
}
Related
What i am doing::
I am opening a camera onclick of item from actionbar menu
I am capturing the image and setting it in a listview
What is happening::
Say i have captured 10 images and set it in listview
next time i run my code, i am able to find the images i took last
time, and it dosen't start from groundup
What i am trying to do:
say i captured 10 images and set in listview
next time i start the app and start capturing the image it should add
freshly captured images to listview and not display the old images
i am not telling i have to delete these images but i the app i want
to show newly captured images everytime
MainActivity.java
public class MainActivity extends ListActivity {
private static final int CAMERA_CAPTURE = 20;
ArrayList<String> listOfImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayCapturedImagesFromCamera();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_camera) {
startCameraCapture();
return true;
}
return super.onOptionsItemSelected(item);
}
private void startCameraCapture() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = CreateImageFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(photoFile != null)
{
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
}
}
}
private File CreateImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Image_" + timeStamp + "_";
File storageDirectory = getExternalFilesDir("");
File image = File.createTempFile(imageFileName, ".jpg",storageDirectory);
return image;
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case CAMERA_CAPTURE:
if(resultCode == RESULT_OK)
{
DisplayCapturedImagesFromCamera();
}
break;
}
}
private void DisplayCapturedImagesFromCamera() {
// TODO Auto-generated method stub
File myPath = getExternalFilesDir(null);
listOfImages = new ArrayList<String>();
try
{
for(File f: myPath.listFiles()) {
listOfImages.add(f.getAbsolutePath());
}
AdptAddjobsGallery adapter = new AdptAddjobsGallery(MainActivity.this,listOfImages);
setListAdapter(adapter);
}
catch(Exception ex)
{
Log.w("Error", ex.getMessage());
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cust_dialog);
dialog.setTitle("Image ");
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
// set the custom dialog components - text, image and button
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageBitmap(bitmap);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
}
AdptAddjobsGallery.java
public class AdptAddjobsGallery extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> listOfImages;
public AdptAddjobsGallery(Activity context, ArrayList<String> listOfImages) {
super(context, R.layout.adpt_addjobs_gallery, listOfImages);
// TODO Auto-generated constructor stub
this.context=context;
this.listOfImages = listOfImages;
}
public View getView(int position,View view,ViewGroup parent) {
ViewHolder holder;
if(view == null)
{
LayoutInflater inflater=context.getLayoutInflater();
view =inflater.inflate(R.layout.adpt_addjobs_gallery, null,true);
holder = new ViewHolder();
holder.imageView = (ImageView) view.findViewById(R.id.selfie);
holder.txtTitle = (TextView) view.findViewById(R.id.fileName);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
File f = new File(listOfImages.get(position));
holder.txtTitle.setText(f.getName());
holder.imageView.setImageBitmap(bitmap);
return view;
};
}
class ViewHolder {
TextView txtTitle;
ImageView imageView;
}
try this, using file.lastmodified() method.
private ArrayList<String> getRecentImages(long from, long to,
ArrayList<String> list) {
ArrayList<String> sortedList = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
File file = new File(list.get(i));
long modified = file.lastModified();
if (modified > from && modified <= to) {
sortedList.add(list.get(i));
}
}
return sortedList;
}
I have this following activity class. This is the shopping cart class where product gets added to or removed from it. The operation works fine, however i am having a strange issue with it. The problem starts whenever i delete all the products from the cart and go to another activity and return back to the cart activity irrespective of adding or removing items from the cart there is always a product left inside the cart. every time I remove that particular item it shows that it is removed and product disappears from the cart but when i return back again i find that single removed product staying in the cart. I can't find out the cause of this. Somebody please help me with this.
public class Secondscreen extends Activity {
private Context mContext;
int total = 0;
ArrayList<Listitem> arrayList = new ArrayList<Listitem>();
BaseAdapter adapter = null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv = (ListView) findViewById(R.id.listView1);
// TextView showCartContent = (TextView) findViewById(R.id.showCart);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
Button addmorebtn = (Button) findViewById(R.id.moreitems);
final Controller aController = (Controller) getApplicationContext();
int cartSize = aController.getCart().getCartSize();
// initialize product variables and add item objects to the arraylist
if (cartSize > 0) {
for (int i = 0; i < cartSize; i++) {
String pName = aController.getCart().getProducts(i)
.getProductName();
int pPrice = aController.getCart().getProducts(i)
.getProductPrice();
int pQuantity = aController.getCart().getProducts(i)
.getProductQuantity();
String pDisc = aController.getCart().getProducts(i)
.getProductDesc();
// int pID =aController.getCart().getProducts(i).getId();
// total calculated
total = total + (pPrice * pQuantity);
Listitem item = new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", "" + pQuantity);
Log.e("Intem's quantity", "" + item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""
+ arrayList.get(i).getQuantity());
}
showtotal.setText("" + total);
}
adapter = new BaseAdapter() {
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView( final int position, View view,
ViewGroup viewgroup) {
if (view == null) {
view = inflater.inflate(R.layout.pattern, null);
}
TextView tv = (TextView) view.findViewById(R.id.nameview);
TextView tv2 = (TextView) view.findViewById(R.id.pdesc);
TextView tv3 = (TextView) view.findViewById(R.id.priceView);
TextView tv4 = (TextView) view.findViewById(R.id.quantityView);
Button btn = (Button) view.findViewById(R.id.patternButton);
// Remove button actions
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore = arrayList.get(position).getPrice();
int tempstore2 = arrayList.get(position).getQuantity();
//calculation of total
total = total - (tempstore * tempstore2);
adapter.notifyDataSetChanged();
showtotal.setText("" + total);
ModelProducts tempProductObject = aController
.getProducts(position);
//
// int pID =aController.updateProduct(position).getId();
// Log.e("buttonid", ""+pID);
// aController.removeButtonId(position).getId();
aController.getCart().removeProducts(tempProductObject);
arrayList.remove(tempProductObject);
arrayList.remove(position);
adapter.notifyDataSetChanged();
// FirstScreen obj=new FirstScreen();
// obj.onCreate(savedInstanceState);
// int cartSize = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText("" + arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(String.valueOf(arrayList.get(position)
.getQuantity()));
return view;
}
};
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
// int cartSize2 = aController.getCart().getCartSize();
if (cartSize == 0) {
Log.e("emptycartmethod", "I am in empty cart sate");
aController.getCart().getCartlist().clear();
// Intent intent = new Intent(Secondscreen.this, FirstScreen.class);
// startActivity(intent);
finish();
}
// Third Button Action
thirdBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), Thirdscreen.class);
startActivity(i);
}
});
// AddMoreItem Button Action
addmorebtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
I suggest to store the quantity in the bundle. during the rebuilding of the Activity you can get the data from the Bundle and set the correct value inside the oncreate method using getSavedInstanceState.
I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}
yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)
I am trying to use the following code to put a ListView with a custom ListAdapter into an AlertDialog. Currently the activity will display the AlertDialog, but with no ListView displayed:
public class EditMindMapActivity extends Activity {
private Button NewObjectButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_mind_map);
// Assign external resources
NewObjectButton = (Button)findViewById(R.id.button9);
// Set the listener for the interact button
NewObjectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//create text field for user input
final EditText textField = new EditText(EditMindMapActivity.this); //the ed..this might be wrong
/* Create selection images ListView */
//just for placeholding really
ListView listView1 = new ListView(EditMindMapActivity.this);
listView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
listView1.setCacheColorHint(00000000);
ArrayList<Drawable> images = new ArrayList<Drawable>();
//fill up the list of images
images.add(getResources().getDrawable( R.drawable.shape01 ));
images.add(getResources().getDrawable( R.drawable.shape02 ));
images.add(getResources().getDrawable( R.drawable.shape03 ));
images.add(getResources().getDrawable( R.drawable.shape04 ));
images.add(getResources().getDrawable( R.drawable.shape05 ));
images.add(getResources().getDrawable( R.drawable.shape06 ));
images.add(getResources().getDrawable( R.drawable.shape07 ));
images.add(getResources().getDrawable( R.drawable.shape08 ));
// add to the list here
CustomListAdapter01 adapter = new CustomListAdapter01(images, EditMindMapActivity.this);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new ListView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> listView, View itemView, int position, long itemId)
{
//nothing
//probably set some variable
}
});
/* ^^^^^^^^^^^ */
/* Display Select Image AlertDialog */
//may want to make this an external function
// 1. Instantiate an AlertDialog.Builder with its constructor
final AlertDialog.Builder builder = new AlertDialog.Builder(EditMindMapActivity.this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("where will this be?")
.setView( listView1 )
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'ok', set imageLocation and ask the user to name the object ->
//this int holds the selected image location
final int imageLocation = R.drawable.shape05;
//final int imageLocation = listView1
/* Display Input Text AlertDialog */
//might have problem because of overwriting previous builder methods
builder.setMessage("Enter a name for the New Object")
.setView(textField)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'ok', create the object specified ->
//need this to reference mindMapView and access it's arrays
MindMapView mindMapView = (MindMapView)findViewById(R.id.MindMapView);
//get the string from the input, set it to the label of the new object
mindMapView.mindMapArrayListLabels.add( textField.getText().toString() );
//add the correct image.
mindMapView.mindMapArrayListImgs.add(imageLocation);
//move the index to the end position of the arrays
mindMapView.imageIndex = (mindMapView.mindMapArrayListLabels.size() - 1);
//redraw the view
mindMapView.invalidate();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'cancel', don't do anything
}
})
.setTitle("Might not need this")
.show();
/* ^^^^^^^^^^^ */
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'cancel', don't do anything
}
})
.setTitle("Choose an image:")
.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.edit_mind_map, menu);
return true;
}
}
Here is my CustomListAdapter01 class:
public class CustomListAdapter01 extends BaseAdapter {
//contains all of the images that will be displayed
ArrayList<Drawable> images;
Context context;
public CustomListAdapter01(ArrayList<Drawable> images, Context context) {
super();
// TODO Auto-generated constructor stub
this.images = images;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#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 View getView(int position, View convertView, ViewGroup parent)
{
Drawable image = images.get(position);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
ImageView imageView = (ImageView)convertView.findViewById(R.id.image);
imageView.setBackgroundDrawable(image);
return convertView;
}
}
Here is the XML file 'child_layout':
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Any help would be appreciated.
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
should be the below as the adapter needs to know the size of the list:
#Override
public int getCount() {
// TODO Auto-generated method stub
images.size();
}
I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}
Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?
In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.
the only thing I can see not right are these methods:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
These methods should return proper values.
items.get(position) and position respectively.