how to send string array one class to another class in android - java

MainMenulist.java In this class string array store all values public String[] itemcodes; i want access itemcodes to Main.java
Main.java
JSONArray json = jArray.getJSONArray("mainmenu");
list=(ListView)findViewById(R.id.mainmenulist);
adapter=new MainMenulist(this, json);
list.setAdapter(adapter);
MainMenulist.java
public class MainMenulist extends BaseAdapter {
protected static Context Context = null;
int i;
public String editnewmainmenu,menuname;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname,itemcode;
public String[] itemnames,itemcodes;
HashMap<String, String> map = new HashMap<String, String>();
public MainMenulist(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.itemcodes=new String[imageArrayJson.length()];
try {
for (i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("menuimage");
itemname = image.getString("menuname");
itemcode=image.getString("menucode");
itemnames[i] = itemname;
itemcodes[i]=itemcode;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(itemnames[i]);
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
vi = inflater.inflate(R.layout.mainmenulistview, null);
final TextView text = (TextView) vi.findViewById(R.id.menutext);
ImageView image = (ImageView) vi.findViewById(R.id.menuimage);
System.out.println(itemcodes[position]);
image.setImageBitmap(bmps[position]);
text.setText(itemnames[position]);
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(itemcodes[position].equals("1"))
{
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println("prakash");
Context.startActivity(intent);
}
else {
Toast.makeText(Context, "This Feauture is not yet Implemented",4000).show();
}
}
});
return vi;
}
}
MainMenulist.java System.out.println(itemcodes[position]); here i print all the codes .no w i want print same result in Main.java

Write a bean which implements serlizable,write setter and getter method for your array(itemnames) as follows
class Bean implements Serializable{
String itemnames[];
public Hashtable getItemnames() {
return itemnames;
}
public void setItemnames(String itemnames[]) {
this.itemnames= itemnames;
}
}
And write foollowing code in calling activity
Bean b = new Bean();
b.setItemnames(itemnames);
Intent i=new Intent();
i.setClass(A.this,B.class);
i.putExtra("itemnames", b);
startActivity(i);
And retrieve in called activity as follows
Bean obj = (Bean) getIntent().getSerializableExtra("itemnames");// TypeCasting
String itemname[] = (Hashtable) obj.getItemnames();

There are two ways to do this:
In your code:
public String[] itemnames,itemcodes; make that arrays as static like below
public static String[] itemnames,itemcodes;
And then use `Main.java` file by calling:
System.out.println(MainMenulist.itemcodes[position]);
System.out.println(MainMenulist.itemnames[position]);
2) Parse JSON in Main.java which you have pass to MainMenulist.java
public MainMenulist(Context context, JSONArray imageArrayJson)

Related

My get method is returning 0 even though it has a value

So I have two classes. I'm trying to send integer data from one class to the other with a get method (getInputTime). The variable I'm returning inside the get method has a value. But when I use the get method inside of the other class called TimeActivity it just returns 0.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private static final String TAG = "CustomAdapter";
private ArrayList<Integer> mWorkTW = new ArrayList<>();
private ArrayList<Integer> mWorkET = new ArrayList<>();
private ArrayList<Integer> mRestTW = new ArrayList<>();
private ArrayList<Integer> mRestET = new ArrayList<>();
private Context mContext;
private int numberOfIntervals;
public CustomAdapter() {
}
public CustomAdapter(Context context, ArrayList<Integer> mWorkTW, ArrayList<Integer> mWorkET, ArrayList<Integer> mRestTW, ArrayList<Integer> mRestET, int numberOfIntervals) {
this.mWorkTW = mWorkTW;
this.mWorkET = mWorkET;
this.mRestTW = mRestTW;
this.mRestET = mRestET;
this.mContext = context;
this.numberOfIntervals = numberOfIntervals;
//this.inputTimeIntegerWET = inputTimeIntegerWET;
Log.d(TAG, "CustomAdapter: " + numberOfIntervals);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View customView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.time_row, viewGroup, false);
ViewHolder holder = new ViewHolder(customView, new InputTextListener());
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
Log.d(TAG, "onBindViewHolder: called");
viewHolder.workTextView.setText(R.string.work_text_view);
viewHolder.restTextView.setText(R.string.rest_text_view);
viewHolder.workEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
viewHolder.workEditText.setHint("");
else
viewHolder.workEditText.setHint(mWorkET.get(viewHolder.getAdapterPosition()));
}
});
viewHolder.restEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
viewHolder.restEditText.setHint("");
else
viewHolder.restEditText.setHint(mRestET.get(viewHolder.getAdapterPosition()));
}
});
}
#Override
public int getItemCount() {
Log.d(TAG, "" + numberOfIntervals);
return numberOfIntervals;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public InputTextListener inputTextListener;
TextView workTextView;
EditText workEditText;
TextView restTextView;
EditText restEditText;
ConstraintLayout parentLayout;
public ViewHolder(#NonNull View itemView, InputTextListener inputTextListener) {
super(itemView);
workTextView = itemView.findViewById(R.id.workTextView);
workEditText = itemView.findViewById(R.id.workEditText);
restTextView = itemView.findViewById(R.id.restTextView);
restEditText = itemView.findViewById(R.id.restEditText);
parentLayout = itemView.findViewById(R.id.parentLayout);
this.inputTextListener = inputTextListener;
workEditText.addTextChangedListener(inputTextListener);
}
}
class InputTextListener implements TextWatcher {
String inputTimeString;
int inputTime;
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
public HashMap<String, Integer> getHashMap() {
return hashMap;
}
public InputTextListener() {
}
public void setHashMap(HashMap<String, Integer> hashMap) {
this.hashMap = hashMap;
}
public int getInputTime() {
return inputTime;
}
public void setInputTime(int inputTime) {
this.inputTime= inputTime;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
Log.d(TAG, "onTextChanged: I've made it to here!");
inputTimeString = s.toString().trim();
inputTime = Integer.parseInt(inputTimeString);
setInputTime(inputTime);
// hashMap.put("EDITTEXT VALUE", inputTime);
Log.d(TAG, "onTextChanged: " + inputTime);
int bla = inputTime + 2;
Log.d(TAG, "onTextChanged: " + bla);
Log.d(TAG, "onTextChanged: " + hashMap.containsKey("EDITTEXT VALUE"));
Log.d(TAG, "onTextChanged: " + hashMap.get("EDITTEXT VALUE"));
Log.d(TAG, "onTextChanged: "+ getInputTime());
//setHashMap(hashMap);
} catch (NumberFormatException NFE) {
mWorkET = null;
}
}
#Override
public void afterTextChanged(Editable s) {
}
}
}
public class TimeActivity extends AppCompatActivity {
public static final String TAG = TimeActivity.class.getSimpleName();
private int numberOfIntervals;
private ArrayList<Integer> WTV = new ArrayList<>();
private ArrayList<Integer> WET = new ArrayList<>();
private ArrayList<Integer> RTV = new ArrayList<>();
private ArrayList<Integer> RET = new ArrayList<>();
private int inputTime;
// private String yusuf = "5";
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu, menu);
Drawable continueImageDrawable = menu.findItem(R.id.continueItem).getIcon();
continueImageDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
//Every non-transparent pixel will be turned into white.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.continueItem:
CustomAdapter a = new CustomAdapter();
CustomAdapter.InputTextListener i = a.new InputTextListener();
//HashMap<String, Integer> hashMap = i.getHashMap();
//inputTime = hashMap.get("EDITTEXT VALUE");
inputTime = i.getInputTime();
// Log.d(TAG, "onOptionsItemSelected: " + hashMap.get("EDITTEXT VALUE"));
//Log.d(TAG, "onOptionsItemSelected: " + hashMap.containsKey("EDITTEXT VALUE"));
Log.d(TAG, "onOptionsItemSelected: " + inputTime);
retrieveInputTime(inputTime);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
Log.d(TAG, "onCreate: Started");
View timeRowLayout = findViewById(R.id.parentLayout);
Intent intent = getIntent();
numberOfIntervals = intent.getIntExtra("Interval Count", numberOfIntervals);
Log.d(TAG, "" + numberOfIntervals);
initializeViews();
}
private void retrieveInputTime(int inputTime) {
Log.d(TAG, "retrieveInputTime: " + inputTime);
Intent intent2 = new Intent(this, ClockActivity.class);
if (inputTime > 0) {
intent2.putExtra("Input Time", inputTime);
startActivity(intent2);
Log.d(TAG, "retrieveInputTime: The data has been retrieved" + inputTime);
} else {
Toast.makeText(this, "Must enter a whole number 2", Toast.LENGTH_SHORT).show();
}
}
private void initializeViews() {
Log.d(TAG, "initializeViews: Preparing views");
//Make sure they can change through the R.strings
WTV.add(R.string.work_text_view);
WET.add(R.string.default_time_value);
RTV.add(R.string.rest_text_view);
RET.add(R.string.default_time_value);
initializeRecyclerView();
}
private void initializeRecyclerView() {
Log.d(TAG, "initializeRecyclerView: Initialize RecyclerView");
RecyclerView intervalRecyclerView = findViewById(R.id.intervalRecyclerView);
CustomAdapter adapter = new CustomAdapter(this, WTV, WET, RTV, RET, numberOfIntervals);
intervalRecyclerView.setAdapter(adapter);
intervalRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I expect for the getInputTime method to return the correct value inside the TimeActivity class
I see you use getInputTime() in two places:
inside onTextChanged() it is preceded by setInputTime() so it should has value there
inside onOptionsItemSelected() it is called right after creating a new object via InputTextListener(). No initialization is done besides calling the default constructor. inputTime should be 0 at this point.
The CustomAdapater instance that you are referring to in onOptionsItemSelected isn't the same as the one you are initializing for your recyclerView in onCreate.
Look:
CustomAdapter a = new CustomAdapter();
CustomAdapter.InputTextListener i = a.new InputTextListener();
inputTime = i.getInputTime();
You are creating new instance of CustomAdapter then creating new instance of InputTextListener (zero connection between these objects so far), calling getInputTime() on that object will obviously return 0, since it's the default value of int in java.
Anyway, I can't really see the point for using recyclerView in your code.
First of all I want to thank everyone for trying to help solve the problem but I finally solved. The solution is to make the inputTime variable inside the InputTextListener class static. But since it's an inner class I had to make the InputTextListener class it's own class. If you have any thoughts or questions just comment down below.

Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent to activity

I m getting this error in my code.
Please help me.
My code is as follows. I don't know how to solve this. When I click on the add button I want to add all data to the model class and that class should be filled with the list array in main activity.
public class MainActivity extends Activity implements DataTransferInterfase{
private Button btnSelect,btnShow;
public int REQUEST_CAMERA=1;
public int SELECT_IMAGE=0;
private GridView gridview;
private CustomAdapter gridAdaptor;
public TextView tvcounter;
public ImageItemBin imageItemBin;
private Uri mCapturedImageUri;
public static ArrayList<ImageItemBin> publicSelectedImage=new ArrayList<ImageItemBin>();
public ArrayList<ImageItemBin> showImagelist=new ArrayList<ImageItemBin>();
public Uri ImageUri;
private int count=publicSelectedImage.size();
private int coloumn=3;
private int row=count/coloumn;
public String imgPath="";
private Uri fileUri; // file url to store image
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect=(Button)findViewById(R.id.btnselect);
btnShow=(Button)findViewById(R.id.btnShow);
tvcounter=(TextView)findViewById(R.id.tvcounter);
publicSelectedImage=new ArrayList<ImageItemBin>();
//showImagelist=new ArrayList<ImageItemBin>();
showImagelist=new ArrayList<ImageItemBin>();
gridview=(GridView) findViewById(R.id.gridLayout_main);
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
//gridAdaptor(R.layout.custom_grid_item_layout,getView());
//gridLayout.addView(gridAdaptor.getView());
//gridLayout.addView(inflater.inflate(R.layout.custom_grid_item_layout,null));
//gridLayout.addView(img);
//tvcounter.setText(CountRecord(imageItemBin));
//tvcounter.setText(CustomAdapter.result+"");
showImagelist.add(CustomAdapter.showBin);
tvcounter.setText(showImagelist.size());
//showImagelist.add(CustomAdapter.result);
//tvcounter.setText(counter);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//custom dialogBox
final Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_layout);
dialog.setTitle("Select from..");
//set the custom dialog components
TextView txtmsg=(TextView)dialog.findViewById(R.id.txtmsg);
Button btnGallaery=(Button)dialog.findViewById(R.id.btngallery);
Button btnCamara=(Button)dialog.findViewById(R.id.btncamara);
btnGallaery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent image=new Intent();
image.setType("image/*");
image.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(image,"select file"),SELECT_IMAGE);
dialog.dismiss();
}
});
btnCamara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*if(cam.resolveActivity(getPackageManager())!=null){
String filename="temp.jpg";
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,filename);
mCapturedImageUri=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);*/
//cam.putExtra(MediaStore.EXTRA_OUTPUT,setImageUri());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cam.putExtra("Image", fileUri);
startActivityForResult(cam,REQUEST_CAMERA);
dialog.dismiss();
// }
}
});
dialog.show();
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SELECT_IMAGE){
if(resultCode==RESULT_OK && null!=data){
for (int i=0,c=0,r=0;i<count;i++,c++){
if(c==coloumn){
c=0;
r++;
}
}
ImageUri=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(ImageUri.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
}
}
if(requestCode==REQUEST_CAMERA)
{
if(resultCode==RESULT_OK && data!=null){
/*String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(mCapturedImageUri,projection,null,null,null);
int coloumn_index_data=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath=cursor.getString(coloumn_index_data);
Uri selectedImage=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(selectedImage.toString());
publicSelectedImage.add(imageItemBin);*/
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
String stringImage=BitMapToString(mphoto);
// String getimage=getImagePath();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(stringImage);
//imageItemBin.setImage(picturePth.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
//gridAdaptor.notifyDataSetChanged();
// tvcounter.setText(counter);
//publicSelectedImage=selectedImage;
}
}
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
/*private List<ImageItemBin> DisplayImage(){
ImageItemBin itembin=new ImageItemBin();
itembin.getImage();
}*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
/*File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
*/
//File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
// Create the storage directory if it does not exist
/*if (!file.exists()) {
if (!file.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}*/
// Create a media file name
//String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
// Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
} /*else if (type == MEDIA_TYPE_VIDEO) {
//mediaFile = new File(file.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
}*/ else {
return null;
}
return mediaFile;
//return file;
}
private Bitmap previewCapturedImage(Uri file)
{
Bitmap bitmap=null;
try {
// hide video preview
//videoPreview.setVisibility(View.GONE);
//imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(file.getPath(),
options);
return bitmap;
//imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
return bitmap;
}
public String BitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String temp= Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
public static int totalAmt=0;
#Override
public int CountRecord(ImageItemBin bin) {
//for (int i=0;i<count;i++){
totalAmt=totalAmt+1;
// }
return totalAmt;
}
}
I just got it.
here is the way for getting the perfect result.in adapter just add the data.get(position)to countRecord method.
public int CountRecord(ImageItemBin bin)
{
showImagelist.add(showBin);
int size=showImagelist.size();
tvcounter.setText(Integer.toString(size));
btnShow.setText(Integer.toString(size));
return 0;
}
CustomAdaptor.java
public class CustomAdapter extends BaseAdapter {
public static String counter="";
public static int result=0;
Context context;
private int layoutResourceId;
private ArrayList<ImageItemBin> data=new ArrayList<ImageItemBin>();
public static ImageItemBin showBin=new ImageItemBin();
DataTransferInterfase dataTransferInterfase;
String qty,title;
public MainActivity mainActivity;
ImageLoader imageLoader;
DisplayImageOptions options;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity,ArrayList<ImageItemBin> data,DataTransferInterfase dataTransferInterfase){
this.data=data;
this.context=mainActivity;
this.dataTransferInterfase=dataTransferInterfase;
this.mainActivity=mainActivity;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=null;
View rootview=convertView;
if(rootview==null) {
rootview = inflater.inflate(R.layout.custom_grid_item_layout, null);
holder = new Holder();
holder.edttitle = (EditText) rootview.findViewById(R.id.edtTitle);
holder.edtqty = (EditText) rootview.findViewById(R.id.edtQty);
holder.image = (ImageView) rootview.findViewById(R.id.MyimageView);
holder.tvcounter=(TextView)rootview.findViewById(R.id.tvcounter);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
rootview.setTag(holder);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
else
{
holder=(Holder)convertView.getTag();
holder.image.setTag(position);
holder.edttitle.setTag(position);
holder.edtqty.setTag(position);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
String img=data.get(position).getImage();
final String title=data.get(position).getTitle();
final String qty=data.get(position).getQty();
options = getDisplayImageOptions(context, R.mipmap.ic_launcher);
imageLoader.displayImage(img, holder.image, options);
holder.btnadd=(Button)rootview.findViewById(R.id.btnAdd);
final Holder finalHolder = holder;
//public static final ImageItemBin showBin=new ImageItemBin();
holder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(position).setQty(qty);
data.get(position).setTitle(title);
showBin.setImage(data.get(position).getImage());
showBin.setTitle(title);
showBin.setQty(qty);
mainActivity.CountRecord(data.get(position));
}
});
return rootview;
}
static class Holder{
ImageView image;
EditText edtqty;
EditText edttitle;
Button btnadd;
TextView tvcounter;
}
public static DisplayImageOptions getDisplayImageOptions(Context context, int defaultImg) {
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(defaultImg)
.resetViewBeforeLoading(true).showImageForEmptyUri(defaultImg).showImageOnFail(defaultImg)
.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true).build();
return options;
}
}

Using AsyncTask to load images into a adapter for ListView

Hello So I Was Having Problems With My List View That Contains Songs And There AlbumArt and I Want To make an AsyncTask To Get The Album Art In background.
Put Its either giving Me A NullPointer Or The Album Art is Blank Please Help
ImageLoader.java
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private View view;
private Bitmap bitmap = null;
public static BitmapDrawable drawable = null;
Context context;
Cursor cursor;
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
#Override
protected Bitmap doInBackground(Object... parameters) {
// Get the passed arguments here
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, albumId);
ContentResolver res = context.getContentResolver();
InputStream in;
try {
if(bitmap != null)
{
bitmap = null;
if(drawable != null)
{
drawable = null;
}
}
in = res.openInputStream(albumArtUri);
bitmap = BitmapFactory.decodeStream(in);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 1280, 720, false);
// bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
drawable = new BitmapDrawable(context.getResources(), resizedBitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
drawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.default_artwork);
};
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && view != null) {
ImageView albumArt = (ImageView) view.getTag(R.id.iconlist);
albumArt.setImageBitmap(bitmap);
}
}
}
SongAdapter.java
public class SongAdapter extends CursorAdapter implements SectionIndexer{
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final LayoutInflater mInflater;
public SongAdapter(Context context, Cursor c, int textViewResourceId,
List<String> objects) {
super(context, c,textViewResourceId);
new ImageLoader().execute();
mInflater=LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title1 = (TextView) view.findViewById(R.id.titlelist);
TextView artist1 = (TextView) view.findViewById(R.id.artistlist);
ImageView album1 = (ImageView) view.findViewById(R.id.iconlist);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
StringBuilder titleBuild = new StringBuilder();
titleBuild.append(title);
if(titleBuild.length() > 35)
{
titleBuild.setLength(32);
title = titleBuild.toString()+"...";
}
else
{
title = titleBuild.toString();
}
StringBuilder artistBuild = new StringBuilder();
artistBuild.append(artist);
if(artistBuild.length() > 35)
{
artistBuild.setLength(32);
artist = artistBuild.toString()+"...";
}
else
{
artist = artistBuild.toString();
}
album1.setImageDrawable(ImageLoader.drawable);
title1.setText(title);
artist1.setText(artist);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.rowlayout, parent, false);
}#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(String.valueOf(( getItem(j))), String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(String.valueOf(getItem(j)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
Now This Code Gives Me A Null Pointer So Any Help Would Be Great
Your view object in the Async task is never initialized, atleast I don't see that code. What I think you could do is launch a new AsyncTask for every "new" view you're creating in your adapter. You would need to make the async task have a reference to the imageview you want to populate though. One way to do this is like this.
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private WeakReference<ImageView> mReference;
private View view;
private Bitmap bitmap = null;
public static BitmapDrawable drawable = null;
Context context;
Cursor cursor;
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
public ImageLoader(ImageView imageView) {
mReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(Object... parameters) { ... your code }
#Override
protected Void onPostExecute(Bitmap bitmap) {
if(mReference != null) {
if(bitmap != null) {
ImageView view = mReference.get();
// note that this could still return null if the view or the reference has been
// garbage collected which it could be since it is a weak reference, so you should
// always check the status in this case.
//do what you want with the image view.
}
}
}
then in your adapter do something like this.
public class SongAdapter extends CursorAdapter implements SectionIndexer{
...other code...
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title1 = (TextView) view.findViewById(R.id.titlelist);
TextView artist1 = (TextView) view.findViewById(R.id.artistlist);
ImageView album1 = (ImageView) view.findViewById(R.id.iconlist);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
StringBuilder titleBuild = new StringBuilder();
titleBuild.append(title);
if(titleBuild.length() > 35)
{
titleBuild.setLength(32);
title = titleBuild.toString()+"...";
}
else
{
title = titleBuild.toString();
}
StringBuilder artistBuild = new StringBuilder();
artistBuild.append(artist);
if(artistBuild.length() > 35)
{
artistBuild.setLength(32);
artist = artistBuild.toString()+"...";
}
else
{
artist = artistBuild.toString();
}
<---->
// new code
new ImageLoader(album1).execute();
// old code album1.setImageDrawable(ImageLoader.drawable);
title1.setText(title);
artist1.setText(artist);
}
}
I've used a similar technique in a grid view and it's cool because you can actually see each image view being populated.
Hope that helps!

How to showstrings in Listview in Android

I want to show some contacts information those are stored in a file in the list view.I want each contact to be shown in a separate cell rather than all together in a same place.Now all the contacts are showing in a single cell in the list view.I used a special character to check the end of a contact information.
Thanks in advance :)
Here is my code:
public void show_contacts()
{
final ListView listview = (ListView) findViewById(R.id.listview);
final ArrayList<String> list = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
String data_read="";
String FILENAME = "myfile.txt";
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = null;
String s1="";
try {
fis = openFileInput("myfile.txt");
byte[] buffer = new byte[1];
while (fis.read(buffer) != -1) {
if(s1.endsWith("."))
{
data_read=fileContent.toString();
list.add(data_read);
}
else
s1+=buffer.toString();
fileContent.append(new String(buffer));
}
} catch (Exception e) {
e.printStackTrace();
}
data_read=fileContent.toString();
list.add(data_read);
listview.setAdapter(adapter);
}
public void Write_to_file(String cName2,String cNumber2)
{
String string=cName2+"--"+cNumber2;
String FILENAME="myfile.txt";
FileOutputStream fos = null;
Context c=this.getBaseContext();
try {
String s=".";
fos = c.openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(string.getBytes());
fos.write(s.getBytes());
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
My wish is you don't write the contact name into text file you Just write your Contacts in the custom Class like
public class Sample {
private String listitem1;
private String listitem2;
public String getListitem1() {
return listitem1;
}
public void setListitem1(String listitem1) {
this.listitem1 = listitem1;
}
public String getListitem2() {
return listitem2;
}
public void setListitem2(String listitem2) {
this.listitem2 = listitem2;
}
}
And use this custom adapter in your program...
public class CustomAdapter extends ArrayAdapter<Sample> {
public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;
public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
super(context, resource);
this.mlist = mlist;
this.context = context;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getPosition(Sample item) {
return super.getPosition(item);
}
#Override
public Sample getItem(int position) {
return mlist.get(position);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.listitem, null);
TextView text1 = (TextView) convertView.findViewById(R.id.item1);
TextView text2 = (TextView) convertView.findViewById(R.id.item2);
text1.setText(mlist.get(position).getListitem1());
text2.setText(mlist.get(position).getListitem2());
return convertView;
}
}
And use this code into your Activity....
private ArrayList<Sample> mListItems;
private PullToRefreshListView mPullRefreshListView;
private CustomAdapter mAdapter;
private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_list);
mListItems= new ArrayList<Sample>();
mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
Calculation();
mPullRefreshListView.setAdapter(mAdapter);
}
private void Calculation() {
for(int i=0;i<mStrings.length;i++)
{
Sample sample = new Sample();
sample.setListitem1(mStrings[i]);
sample.setListitem2(mStrings[i]);
mListItems.add(sample);
}
}
And you just replace with you Contact Name and Number in the Above sample..

Loading images in listview asynchronously with callback

I'm using Parse in my app, and in order to load my 'profile' images, I need to retrieve a so called Parsefile. When the Parsefile is downloaded it uses a callback to notify when it's done. Now this is generally a nice way to do things but I encountered a problem with this when using a Listview and downloading the images with an Asynctask.
The problem is as follows:
In my ListView adapter in the getView method, I create an AsyncTask and execute it, this AsyncTask starts the retrieveProfileImage(callBack) function. In my callback I simply start a Runnable on the UI thread to update the ImageView in the View with the new (retrieved Image). The problem however as it seems, is the fact that as soon as I start my AsyncTask, the View is returned. So I can't set the other images to the correct row. I hope my code demonstrates my problem more clearly.
The ListAdapter:
public class FriendListAdapter extends ArrayAdapter<Profile> {
private int resource;
private Context context;
private List<Profile> friends;
private Profile fProfile;
private Bitmap profileImageBitmap;
private ProgressBar friendImageProgressBar;
//ui
private ImageView friendImage;
public FriendListAdapter(Context context, int resource,
List<Profile> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.friends = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView friendName = null;
friendImage = null;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(R.layout.friendslist_row, null);
friendName = (TextView) rowView.findViewById(R.id.fName);
friendImage = (ImageView) rowView
.findViewById(R.id.fImage);
friendImageProgressBar = (ProgressBar) rowView.findViewById(R.id.friendImageProgressBar);
} else {
friendName = (TextView) convertView.findViewById(R.id.fName);
friendImage = (ImageView) convertView.findViewById(R.id.fImage);
friendImageProgressBar = (ProgressBar) convertView.findViewById(R.id.friendImageProgressBar);
}
fProfile = friends.get(position);
DownloadProfileImage dImg = new DownloadProfileImage();
dImg.execute();
friendName.setText(fProfile.getName());
return rowView;
}
private class DownloadProfileImage extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... arg0) {
Log.d("logpp", "Starting download image for " + fProfile.getName());
fProfile.retrieveProfileImage(new ProfileImageCallback());
return null;
}
}
private class ProfileImageCallback extends GetDataCallback {
#Override
public void done(byte[] bytearray, ParseException e) {
if (e == null) {
Log.d("logpp", "Done downloading image for " + fProfile.getName() + ". Setting bitmap to:" +
" " + friendImage.getId());
profileImageBitmap = BitmapManager
.getBitmapFromByteArray(bytearray);
((Activity) context).runOnUiThread(new UpdateUi());
}
}
}
private class UpdateUi implements Runnable {
#Override
public void run() {
friendImage.setImageBitmap(profileImageBitmap);
friendImage.setVisibility(View.VISIBLE);
friendImageProgressBar.setVisibility(View.INVISIBLE);
}
}
}
The retrieveProfileImage method:
public void retrieveProfileImage(GetDataCallback callBack) {
this.image.getDataInBackground(callBack);
}
I hope someone can help me with this one.
Regards,
Tim
i solved this problem by following code
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.answer_item, null);
TextView name = (TextView) convertView.findViewById(R.id.textView_ans_user_name);
TextView body = (TextView) convertView.findViewById(R.id.textView_ans_user_body);
TextView timestamp = (TextView) convertView.findViewById(R.id.textView_ans_user_timestamp);
final CircularImageView thumbnail = (CircularImageView) convertView.findViewById(R.id.imageView_ans_user);
Parse_answer_model ans = answers.get(position);
name.setText(ans.getAns_by());
body.setText(ans.getAns_body());
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdfAmerica.setTimeZone(TimeZone.getDefault());
String sDateInAmerica = sdfAmerica.format(ans.getCreatedAt());
timestamp.setText(sDateInAmerica);
ParseQuery<User> query = ParseQuery.getQuery("_User");
query.whereEqualTo("username", ans.getAns_by());
query.getFirstInBackground(new GetCallback<User>() {
public void done(User user, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
img.DisplayImage(user.getprofile_pic_url(), thumbnail, false);
} else {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
put your imageview as final dont make it global and you get image url from geturl() method, it is as defined by parse you can use below example
ParseFile fileObject = (ParseFile) object.get("image_file");
User user = new User();
user = (User) ParseUser.getCurrentUser();
user.setProfile_pic_url(fileObject.getUrl().toString());
user.saveInBackground();
update
last day i found new solution you can get user's data which related to parse object by following code and made some changes in model class,too.
void getchats() {
pd.show();
ParseQuery<Parse_chat_dialogs> query = ParseQuery.getQuery("chat_dialogs");
query.addDescendingOrder("updatedAt");
query.whereContains("users", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<Parse_chat_dialogs>() {
public void done(List<Parse_chat_dialogs> dilogs, ParseException e) {
if (e == null) {
pd.hide();
dialoglist = (ArrayList<Parse_chat_dialogs>) dilogs;
adp = new ChatDialogAdapter(Chat_list.this, dialoglist);
list.setAdapter(adp);
for (int i = 0; i < dialoglist.size(); i++) {
ParseQuery<User> query = ParseQuery.getQuery("_User");
query.whereEqualTo("username", dialoglist.get(i).getUsers().trim()
.replace(ParseUser.getCurrentUser().getUsername(), "").replace(",", ""));
User user = new User();
try {
user = query.getFirst();
dialoglist.get(i).setFirstname(user.getFirstname());
dialoglist.get(i).setLastname(user.getLastname());
dialoglist.get(i).setProfileurl(user.getprofile_pic_url());
adp.notifyDataSetChanged();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} else {
Toast.makeText(Chat_list.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
as in above example i added three new param in parseobejct model class for storing values of user's firstname ,lastname and profile url.
i am also sharing model class for getting more idea
#ParseClassName("chat_dialogs")
public class Parse_chat_dialogs extends ParseObject {
private String firstname;
private String lastname;
private String profileurl;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getProfileurl() {
return profileurl;
}
public void setProfileurl(String profileurl) {
this.profileurl = profileurl;
}
/////////////////////////////////////////////////////////////////////////////
public String getLast_message() {
return getString("last_message");
}
public void setLast_message(String value) {
put("last_message", value);
}
public String getUsers() {
return getString("users");
}
public void setUsers(String value) {
put("users", value);
}
}
How about this!
Instead of using AsyncTask in the adapter class, use it in the MainActivity where you set the adapter for the listview. And in your done method in the Callback or the postExecute update the object/objects and call notifyDataSetChanged().
So, essentially you could have an update method in your adapter class, say, like this,
public void updateObject(int pos, byte[] byteArray){
//Assuming your Profile Object has some member to store this image data
friends.get(pos).setImageData(byteArray); //friends is the list in adapter class and setImageData may be the setter in your Profile object class
notifyDataSetChanged();
}
and in the getView(), you could do something like this
profileImageBitmap = BitmapManager
.getBitmapFromByteArray(friends.get(pos).getImageData);
friendImage.setImageBitmap(profileImageBitmap);

Categories