HashMap<String,String> temp = new HashMap<String,String>(); for pass image - android

for(int i=0;i<StoreparsrData.title.size();i++){
HashMap<String,String> temp = new HashMap<String,String>();
Bitmap bt=Utility.getBitmapFile(StoreparsrData.url.get(i).toString());
ImageView img=(ImageView)findviewbyid(R.id.img);
img.setImageBitmap(bt);
but iwant to convert this img.setImageBitmap(bt); to string so its input for
temp.put("image",image );
temp.put("title",StoreparsrData.title.get(i).toString());
temp.put("description", StoreparsrData.description.get(i).toString());
temp.put("lastbuilddate", StoreparsrData.lastBuildDate.get(0).toString());
list.add(temp);
}
so its show image
Pls Reply me

If I'm understanding your question, why not use:
temp.put("image",StoreparsrData.url.get(i).toString());
Then perform the ImageView lookup when you read from the list
EDIT
Here's another approach:
public class ParseBean {
private ImageView image;
private String title;
private String description;
private String lastBuildDate;
// add getters and setters here
}
...
for(int i=0;i<StoreparsrData.title.size();i++){
HashMap<String,ParseBean> temp = new HashMap<String,ParseBean>();
Bitmap bt=Utility.getBitmapFile(StoreparsrData.url.get(i).toString());
ImageView img=(ImageView)findviewbyid(R.id.img);
img.setImageBitmap(bt);
ParseBean bean = new ParseBean();
bean.setImage(img);
bean.setTitle(StoreparsrData.title.get(i).toString());
bean.setDescription(StoreparsrData.description.get(i).toString());
bean.setLastBuildDate(StoreparsrData.lastBuildDate.get(0).toString());
list.add(bean);
}

Related

how to select first index in listview onCreate()? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to select the first index in listview on first load onCreate. I've try the listView.setSelection(0) but some error occur. this is my code...
public class QandAPractice extends AppCompatActivity {
String qsid;
ListView listView;
ArrayList<String> myqid;
RadioButton r1,r2,r3,r4;
String txtcontent, txtTimer,txtAnskey,txtImg, txtA, txtB, txtC, txtD, txtID;
private static final String TAG_QID = "id";
private static final String TAG_TITLE = "content";
private static final String TAG_TIMER = "timer";
private static final String TAG_IMAGE = "images";
private static final String TAG_QSID = "qsid";
private static final String TAG_KEY = "key";
private static final String TAG_A = "A";
private static final String TAG_B = "B";
private static final String TAG_C = "C";
private static final String TAG_D = "D";
ArrayList<HashMap<String, String>> questions;
Dialog quizDialog;
public int i = 60;
public int loadindex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qand_apractice);
questions = new ArrayList<>();
myqid = new ArrayList<>();
Bundle b = getIntent().getExtras();
setTitle(b.getString("subject"));
qsid = b.getString("qsid");
quizDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
listView = findViewById(R.id.lvquestions);
getJSON(Constants.ROOT_URL+"mobile_question_index.php?qsid="+qsid);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
txtID = ((TextView) view.findViewById(R.id.quiz_id)).getText()
.toString();
txtcontent = ((TextView) view.findViewById(R.id.quiz_content)).getText()
.toString();
txtTimer = ((TextView) view.findViewById(R.id.quiz_timer)).getText()
.toString();
txtAnskey = ((TextView) view.findViewById(R.id.quiz_key)).getText()
.toString();
txtA = ((TextView) view.findViewById(R.id.quiz_A)).getText()
.toString();
txtB = ((TextView) view.findViewById(R.id.quiz_B)).getText()
.toString();
txtC = ((TextView) view.findViewById(R.id.quiz_C)).getText()
.toString();
txtD = ((TextView) view.findViewById(R.id.quiz_D)).getText()
.toString();
txtImg = ((TextView) view.findViewById(R.id.quiz_image)).getText()
.toString();
showQuiz();
}
});
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
}
this is the Error fetch in debug logcat..
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setSelected(boolean)' on a null object reference
at com.example.jhan08.engineeringexclusivereviewer.QandAPractice.onCreate(QandAPractice.java:90)
at android.app.Activity.performCreate(Activity.java:6351)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)
I've read some thread that has the same issue like mine. They use adapter to fix the issue but still in my case this error still occur. Any help is much appreciated.
Do Your Selection after you set Your Adapter to the Listview
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
I think I got the main issue you have faced. You try to select an item before populating the list view. You need to set this after adapter added on the listview.
Add this lines after adding the adapter.
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
or use
listView.setAdapter(adapter);
listView.setItemChecked(0, true)
This will show a toast message for first opening. This should be added after the adapter set.
Iterator myVeryOwnIterator = questions.get(0).keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}

How to set the image of row RecyclerView Adapter

I need to set the image of my row RecyclerView how to add the image of employee I want to convert the String to Bitmap and display the image in an imageView
Activity 1
String name = currentobject.getString("name_related");
String email = currentobject.getString("work_email");
String phone = currentobject.getString("work_phone");
String Img = currentobject.getString("image_small");
byte[] imageAsBytes = Base64.decode(Img.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
employee= new Employee(id,(String)deptArry.get(1),email,phone,decodedByte.toString(),name);
Employees.add(employee);
ClassAdapter how to add the image of employee
public void onBindViewHolder(EmployeeHolder holder, int position) {
Employee employee=EmployeeList.get(position);
holder.id.setText(employee.getId());
holder.name.setText(employee.getName());
holder.phone.setText(employee.getPhone());
holder.Image.set????(employee.getImage());
}
Employee object with getter and setter ...
private String id;
private String name;
private String phone;
private String Image;
Your ViewHolder should have an ImageView as part of it's layout. Right now you are trying to set the image on "Image", but "Image" is type String.
Once you have an ImageView as part of your layout then you can simply call:
imageView.setImageBitmap(decodedByte)

Android: Fetching values from arraylist of map

Photos url links, title, user name are loaded from Parse and packed as map, and then the maps are stored as an arraylist, as follows:
public class Photos
{
private String user_name;
private String photo_title;
private String photo_ref;
public void set_user_name(String name) {this.user_name = name;}
public void set_photo_ref(String photo_ref) {this.photo_ref = photo_ref;}
public void set_photo_title(String photo_title) {this.photo_title = photo_title;}
public String get_user_name() {return user_name;}
public String get_photo_ref() {return photo_ref;}
public String get_photo_title() {return photo_title;}
}
and then downloading from Parse for database,
for (ParseObject photo_data : ob)
{
ParseFile image = (ParseFile) photo_data.get("photo_file");
Photos map = new Photos();
String photo_url = image.getUrl(); map.set_photo_ref(photo_url);
int photo_id = (Integer) photo_data.get("photo_id"); map.set_photo_id(photo_id);
String status = (String) photo_data.get("status"); map.set_photo_status(status);
String photo_user_name = (String) photo_data.get("user_name"); map.set_user_name(photo_user_name);
String photo_title = (String) photo_data.get("photo_title");
if (status.equals("accepted"))
{
map_all_info_photoarraylist.add(map);
}
Question:
How could I create another string array of photo_ref only by fetching from the above map using the method get_photo_ref()
String[] stockArr = new String[map_all_info_photoarraylist.size()];
stockArr = map_all_info_photoarraylist.???????.toArray(stockArr);
Thanks!
If you want an array:
String[] stockArr = new String[map_all_info_photoarraylist.size()];
for(int i =0; i<map_all_info_photoarraylist.size(); i++){
stockArr[i] = map_all_info_photoarraylist.get(i).get_photo_ref();
}

add drawable image To Button

I want to insert images into dynamic buttons, I can get everything other than images. I want my button to display as text+image, but instead I am getting text + androidgraphics.drawable.bitmapdrawable#416e5 etc. Can anyone tell what the mistake is in my code, any help appreciated.
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
int sizeData = 0;
private View addButton;
protected Bitmap myBitmap;
private String image;
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
JSONArray jsonMainNode1 = jsonResponse.getJSONArray("menu");
// JSONObject e = jsonMainNode1.getJSONObject(position);
int lengthJsonArr = jsonMainNode1.length();
for(int i=0; i <lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode1.getJSONObject(i);
String Pid = jsonChildNode.optString("pid".toString());
String Name = jsonChildNode.optString("name").toString();
String Refid=jsonChildNode.optString("refid".toString());
String imagefile = jsonChildNode.getString("image_url");
String resName = imagefile.split("\\.")[2];
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
Drawable image = getResources().getDrawable(resId);
OutputData = Name+image;
str_id = Pid;
LinearLayout buttonContainer=(LinearLayout)findViewById(R.id.btn_container);
Button button = new Button(buttonContainer.getContext());
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
ViewGroup.LayoutParams params = button.getLayoutParams();
//Button new width
params.width = 150;
params.height = 150;
button.setLayoutParams(params);
button.setText(OutputData);
// button.setBackground(itemImage);
button.setTag(Refid);
button.setTextColor(Color.parseColor("#FEFCFF"));
button.setBackgroundResource(R.drawable.button_color);
buttonContainer.addView(button);
Drawable image = getResources().getDrawable(resId);
You are trying to print the image which is a drawable object, So it will only display the address information as you see androidgraphics.drawable.bitmapdrawable#416e5
try
OutputData = Name;
you are setting background for button as
button.setBackgroundResource(R.drawable.button_color); are you sure that the image you expect is same as button_color, It sounds like a color.
you should do something as the following :
OutputData = Name;
then to add the text to the button do the following :
button.setText(OutputData);
and to add the image to the button do the following :
btn.setBackgroundResource(resId);
and give me some feedback
Hope that helps .

show selected listview row image to next activity

I am able to send selected listview text to another activity using xml parsing, but not able to fetch selected image to next activity, here I am placing my code, please find out the reason why I am not getting image to another activity:-
MainActivity Code:-
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = pizzaList.get(position);
Intent in = new Intent(MainActivity.this, SecondActivity.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DESCRIPTION, map.get(KEY_DESCRIPTION));
in.putExtra(KEY_THUMB_URL, map.get(KEY_THUMB_URL));
in.putExtra(KEY_COST, map.get(KEY_COST));
startActivity(in);
}
});
SecondActivity Code:-
Intent in = getIntent();
final String title = in.getStringExtra(KEY_TITLE);
final String description = in.getStringExtra(KEY_DESCRIPTION);
final String thumb_url = in.getStringExtra(KEY_THUMBURL);
final String cost = in.getStringExtra(KEY_COST);
TextView title = (TextView) findViewById(R.id.single_title);
TextView description = (TextView) findViewById(R.id.single_description);
TextView cost = (TextView) findViewById(R.id.single_cost);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView thumb = (ImageView) findViewById(R.id.single_image);
title.setText(title);
description.setText(description);
cost.setText(cost);
imageLoader.DisplayImage(thumb_url, thumb);
I think your KEY_THUMB_URL is your url just call this method in your second Activity this is return a bitmap then this bitmap set you on your image view
public static Bitmap loadBitmap(String imgPath) {
String imgUrlStr = imgPath ;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imgUrlStr).getContent());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
final String title = in.getStringExtra(KEY_TITLE);
final String description = in.getStringExtra(KEY_DESCRIPTION);
final String thumb_url = in.getStringExtra(KEY_THUMBURL);
log.i("log_tag","Image URl:"+thumb_url);
final String cost = in.getStringExtra(KEY_COST);
TextView title = (TextView) findViewById(R.id.single_title);
TextView description = (TextView) findViewById(R.id.single_description);
TextView cost = (TextView) findViewById(R.id.single_cost);
ImageView thumb = (ImageView) findViewById(R.id.single_image);
title.setText(title);
description.setText(description);
cost.setText(cost);
Drawable d = LoadImageFromWebOperations(ImageUrl);
imageView.setImageDrawable(d);
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
I found the reason why I was not getting an image into next activity.
I did very small mistake, see line below, which I was using earlier :
final String thumb_url = in.getStringExtra(KEY_THUMBURL);
And now I have tried with:
final String imageUri = in.getStringExtra(KEY_THUMBURL);
Because I am using this variable:
static final String KEY_THUMBURL = "imageUri";

Categories

Resources