Parsing image with JSON from MySQL in android - android

I saw and read a lot of post here for this but I still can't get this images from mysql to my app. I also use one post code and tried to adopt for my app but still the app crashing.
I've used this post How to JSON parse images from mysql and populate listview
private ListView listView;
private StockAdaptor stockAdaptor;
String jsonResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants); //Just a listView, shown below
listView = (ListView) findViewById(R.id.restaurants);
new JsonReadTask().execute("http://link"); //YOUR URL JSON SERVER, IF IT IS DIFFERENT FROM THAT SUPPLIED ABOVE
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true; //No options
}
public void onStart() {
super.onStart();
stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
}
public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
StringBuilder out = new StringBuilder();
BufferedReader breader = new BufferedReader(new InputStreamReader(in));
String cline;
String newLine = System.getProperty("line.separator");
while ((cline = breader.readLine()) != null) {
out.append(cline);
out.append(newLine);
}
return out.toString();
}
private class StockAdaptor extends BaseAdapter { //The stocks list adaptor
class ViewHolder {
TextView name;
TextView menu;
ImageView image;
}
private LayoutInflater layoutInflater;
private RestaurantInformation[] stocks = null; //Array of stocks
public StockAdaptor(Context context) {
super();
layoutInflater = LayoutInflater.from(context);
}
public void setStockList(RestaurantInformation[] stocksinfo) {
this.stocks = stocksinfo;// //////////////LITERALLY THIS
}
#Override
public int getCount() {
return stocks.length;
}
#Override
public Object getItem(int position) {
return stocks[position];
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder; //New holder
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.restaurant_information, null);
holder = new ViewHolder();
// Creates the new viewholder define above, storing references to the children
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.menu = (TextView) convertView.findViewById(R.id.menu);
holder.image = (ImageView) convertView.findViewById(R.id.image);
if (holder.image != null) {
if (holder.image.getDrawable() == null) {
new ImageDownloaderTask(holder.image, null)
.execute(stocks[position].image); //Download the image using the image
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(stocks[position].name);
holder.menu.setText(stocks[position].menu);
return convertView;
}
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (URLUtil.isValidUrl(params[0])) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(getRequest);
final HttpEntity httpentity = response.getEntity();
if (httpentity != null){
InputStream inputStream = null;
try {
inputStream = httpentity.getContent();
jsonResult = strFromStream(inputStream);
Log.i("", jsonResult);
return jsonResult;
} catch (IllegalArgumentException e) {
//
} finally {
httpentity.consumeContent();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.close();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
// build hash set for list view
public void ListDrwaer() {
try {
if (jsonResult!=null) {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
Vector<RestaurantInformation> restaurants = new Vector<RestaurantInformation>();
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantInformation stock = new RestaurantInformation();
stock.name = jsonChildNode.optString("name");
stock.menu = jsonChildNode.optString("menu");
stock.image = jsonChildNode.getString("image");
Log.i("StockLog", stock.name + stock.menu + stock.image);
restaurants.add(stock);
}
RestaurantInformation[] stocks = new RestaurantInformation[jsonMainNode.length()];
int stockscount = jsonMainNode.length();
for (int n = 0; n < stockscount; n++)
{
stocks[n] = restaurants.get(n);
}
stockAdaptor.setStockList(stocks);
listView.setAdapter(stockAdaptor);
} else {
Toast.makeText(getApplicationContext(), "Error; jsonResult null",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView, View view) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//
}
}
}
}
Bitmap downloadBitmap(String url) {
if(URLUtil.isValidUrl(url)){
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
try {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.i("IAE", "in stocks");
return null;
}
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
return null;
}
}
And the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="3dp"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="" />
<TextView
android:id="#+id/menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="" />
</LinearLayout>
</LinearLayout>
The error that I take in LogCat is this.
11-04 07:39:13.880: E/AndroidRuntime(831): FATAL EXCEPTION: main
11-04 07:39:13.880: E/AndroidRuntime(831): Process: com.reserveme, PID: 831
11-04 07:39:13.880: E/AndroidRuntime(831): java.lang.NullPointerException
11-04 07:39:13.880: E/AndroidRuntime(831): at com.reserveme.Restaurants.ListDrwaer(Restaurants.java:198)
11-04 07:39:13.880: E/AndroidRuntime(831): at com.reserveme.Restaurants$JsonReadTask.onPostExecute(Restaurants.java:184)
11-04 07:39:13.880: E/AndroidRuntime(831): at com.reserveme.Restaurants$JsonReadTask.onPostExecute(Restaurants.java:1)
11-04 07:39:13.880: E/AndroidRuntime(831): at android.os.AsyncTask.finish(AsyncTask.java:632)
11-04 07:39:13.880: E/AndroidRuntime(831): at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-04 07:39:13.880: E/AndroidRuntime(831): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-04 07:39:13.880: E/AndroidRuntime(831): at android.os.Handler.dispatchMessage(Handler.java:102)
11-04 07:39:13.880: E/AndroidRuntime(831): at android.os.Looper.loop(Looper.java:136)
11-04 07:39:13.880: E/AndroidRuntime(831): at android.app.ActivityThread.main(ActivityThread.java:5017)
11-04 07:39:13.880: E/AndroidRuntime(831): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 07:39:13.880: E/AndroidRuntime(831): at java.lang.reflect.Method.invoke(Method.java:515)
11-04 07:39:13.880: E/AndroidRuntime(831): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-04 07:39:13.880: E/AndroidRuntime(831): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-04 07:39:13.880: E/AndroidRuntime(831): at dalvik.system.NativeStart.main(Native Method)
Update:
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantInformation stock = new RestaurantInformation(); <--- THIS LINE
stock.name = jsonChildNode.optString("name");
stock.menu = jsonChildNode.optString("menu");
stock.image = jsonChildNode.getString("image");
Log.i("StockLog", stock.name + stock.menu + stock.image);
restaurants.add(stock);
}
UPDATE
This is server side .php file
<?php
$host="localhost"; //replace with database hostname
$username="user"; //replace with database username
$password="pass"; //replace with database password
$db_name="dbname"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from Restaurants";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['Restaurants'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>

I am sorry to say but I don't think the line number you mentioned is line 198.
According to my calculation line nubmer 4 in following code snippet should be line nubmer 198 that is causing the NPE
1 JSONObject jsonResponse = new JSONObject(jsonResult);
2 JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
3 Vector<RestaurantInformation> restaurants = new Vector<RestaurantInformation>();
4 for (int i = 0; i < jsonMainNode.length(); i++)
5 {
6 JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
7 RestaurantInformation stock = new RestaurantInformation();
.........
Check if you are getting the value of jsonMainNode correctly. Base on analysis using your logcat and code, it seems that jsonResponse.optJSONArray("metoxes"); is returning null and without checking for null you are using this in your for loop.
put a if condition for null to check the null value of jsonMainNode before the for loop.
Use if statement like this
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
Vector<RestaurantInformation> restaurants = new Vector<RestaurantInformation>();
if(jsonMainNode == null)
{
Log.e("Inside if", "jsonMainNode is null here");
return;
}
for (int i = 0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantInformation stock = new RestaurantInformation();

Related

Get URL image from MySQL and display on android listView (setImageURI)

I'm new to Android and PHP. I've successfully uploaded the image URI from Android to MySQL and now getting trouble to get the image URI back and display on the listView Activity A. Any help would be greatly appreciated. Thanks a lot.
MySQL
Sending to MySQL:
I'm sending the image uri to server, and store the image path to MySQL, images are saved in PhotoUpload folder.
#Override
protected String doInBackground(String... params) {
for (int index = 0; index < jsonArray.length(); index++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(index);
String strUri = jsonObject.getString("image");
HashMap<String, String> data = new HashMap<String, String>();
data.put(Configs.KEY_IMAGE, getStringImage(Uri.parse(strUri)));
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Configs.SEND, data);
return result;
} catch (Exception e) {
}
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
And now I'm trying to fetch the url from MySQL and display the image into listView, but the image cannot be retrieved out, only String can be retrieved.
Retrieved from server:
public void BuildEditStaffList(final String id) {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.107.115/Android/CRUD/staffRetrieve.php?id=" + id);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
details = jsonObj.getJSONArray(Configs.TAG_RESULTS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String type = c.getString(Configs.TAG_TYPE);
String description = c.getString(Configs.TAG_DESCRIPTION);
String amount = c.getString(Configs.TAG_AMOUNT);
String image = c.getString(Configs.TAG_IMAGE);
int ID = c.getInt(Configs.TAG_ID);
Staff staff = new Staff(ID, type, description, amount, image);
staffs.add(staff);
}
CVAdapter adapter = new CVAdapter(getActivity(), staffs);
listViewEdit.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
CVAdapter:
public class CVAdapter extends ArrayAdapter<Staff> {
Activity context;
List<Staff> staffs;
static class ViewHolder {
public ImageView image;
public TextView type;
public TextView amount;
public TextView description;
}
#Override
public int getCount() {
return staffs.size();
}
public CVAdapter(Activity context, List<Staff> staffs) {
super(context, R.layout.retrieve_staff, staffs);
this.context = context;
this.staffs = staffs;
}
#Override
public Staff getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
ViewHolder v = new ViewHolder();
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.retrieve_staff, null);
v.image = (ImageView)convertView.findViewById(R.id.image);
v.amount = (TextView)convertView.findViewById(R.id.amount);
v.type = (TextView)convertView.findViewById(R.id.type);
v.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(v);
}
holder = (ViewHolder)convertView.getTag();
Log.v("TEST", staffs.get(position).getImage());
holder.image.setImageURI(Uri.parse(staffs.get(position).getImage()));
holder.amount.setText(staffs.get(position).getAmount());
holder.type.setText(staffs.get(position).getType());
holder.description.setText(staffs.get(position).getDescription());
return convertView;
}
}
RetrieveImageAndText.php
<?php
define('HOST','127.0.0.1:3307');
define('USER','root');
define('PASS','');
define('DB','androiddb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect');
$tws = $_GET['id'];
$sql = "select * from staff_benefit WHERE ts_id= '". $tws."' ";
$res = mysqli_query($con,$sql);
$result=array();
while($row=mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'type'=>$row[1],'amount'=>$row[2],'description'=>$row[3],'image'=>$row[4],
'ts_id'=>$row[5]));
}
echo (json_encode(array("result"=>$result)));
mysqli_close($con);
?>
Output
Use a networking library like Volley, Picasso, etc to GET the image over a network call as a Bitmap response and then you can set it to the ImageView via:
holder.image.setImageBitmap(bitmapResponse)
Here is tutorial for using Volley for image requests:
Image Requests with Volley
So I solved it by using Picasso
Just change holder.image.setImageURI(Uri.parse(staffs.get(position).getImage())); to Picasso.with(getContext()).load(staffs.get(position).getImage()).into(holder.image);
Use just a simple codes to get your image
String imageUrl="http://newhabari.000webhostapp.com/db_name/table_name/your_image";
Example
imageUrl="http://newhabari.000webhostapp.com/home_db/nhldb/boeing_787_2.png
Context context=image.getContext();
Picasso.with(context)
.load(imageUrl)
.placeholder(R.drawable.gazetter2)
.error(R.drawable.hands)
.into(image);
return view;
This will give you an image from your db

all images not displaying from the same url

Not all images are displaying when running my app. I am getting from json this result
{"result":[{"id":"1","name":null,"path":"http://api.androidhive.info/json/movies/1.jpg"},{"id":"2","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"32","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"31","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"30","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"29","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"}]}
the first 2 url images are displaying correctly in the app however the rest of the url are not displaying
these are working
[{"id":"1","name":null,"path":"http:\api.androidhive.info\json\movies\1.jpg"},{"id":"2","name":null,"path":"http:\justedhak.comlu.com\images\uploaded_images.jpg"}
these is my code of reading the image
//showlist() is under asynctask prePostExecute
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String url = c.getString(TAG_PATH);
Listitem.add(new Listitem(id,url));
}
GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
// gridView.setAdapter(gridAdapter);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://justedhak.comlu.com/get-data.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
I guess my error is here grid view adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.imageView = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Listitem item = getItem(position);
System.out.println(item.getUrl());
holder.imageTitle.setText(item.getId());
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.fit()
.into(holder.imageView);
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView imageView;
}
}
upload
public void upload()
{
Calendar thisCal = Calendar.getInstance();
thisCal.getTimeInMillis();
// android.util.Log.i("Time Class ", " Time value in millisecinds "+ thisCal);
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
Intent intent = getIntent();
String selectedImage= intent.getStringExtra("imagePath");
Uri fileUri = Uri.parse(selectedImage);
// Uri selectedImage = intent.getData();
System.out.println(fileUri);
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(fileUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageview.setImageBitmap(bitmap);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
System.out.println(width);
System.out.println(height);
getResizedBitmap( bitmap, 200);
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
String image_str = Base64.encodeBytes(byteArray);
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
nameValuePairs.add(new BasicNameValuePair("caption",caption));
nameValuePairs.add(new BasicNameValuePair("name","je"));
nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://justedhak.comlu.com/images/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
final String the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(AddImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});
}catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(AddImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
System.out.println("Error in http connection "+e.toString());
}
}
});
t.start();
}
Getting reference for GridView sample from here, I have just customized and tested loading all your images with it.
Item.java:
public class Item {
String imageUrl;
String title;
public Item(String imageUrl, String title) {
super();
this.imageUrl = imageUrl;
this.title = title;
}
public String getImageUrl() {
return imageUrl;
}
public String getTitle() {
return title;
}
}
CustomGridViewAdapter.java:
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
ArrayList<Item> data = new ArrayList<>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Item item = data.get(position);
holder.txtTitle.setText(item.getTitle());
Picasso.with(context).load(item.getImageUrl()).into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
And MainActivity.java:
customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
gridView.setAdapter(customGridAdapter);
String url = "http://justedhak.comlu.com/get-data.php";
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null && !response.isNull("result")) {
try {
JSONArray jsonArray = response.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject != null && !jsonObject.isNull("path")) {
String imagePath = jsonObject.getString("path");
if (imagePath != null && !imagePath.isEmpty()) {
gridArray.add(new Item(imagePath,"BNK"));
}
}
}
customGridAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
queue.add(jsonObjectRequest);
Other files such as layout... I think you know already
Here is the screenshot
As per my study It's a bug that is reported to be fixed in the next release of the lib.
You can clone the repo of the lib and compile your own jar or wait.
I recommend you to take a look at Glide. Migrating from Picasso is quite trivial, it has better performance and it makes a nice smooth scrolling on lists.
Or try to remove .fit() from picasso.
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.into(holder.imageView);
Hope it will help you.
You should normalize your Uri cause this seems to be to problem here.
Take a look at normalizeScheme() of the Uri class.
It fixes such problems regargng to upper/lowercase letters.
It will convert:
Http:\justedhak.comlu.com\images\uploaded_images.jpg
to
http:\justedhak.comlu.com\images\uploaded_images.jpg
If you want some more details you can take a look at this RFC 2396
Scheme names consist of a sequence of characters beginning with a
lower case letter and followed by any combination of lower case
letters[...]

set ListView on setOnClickListener whit ID

I have listView which show image and text from MySQL DB. So far is ok but now I wonder how to make if some item is clicked to open that ID from database. Example ListView 1 is with id=1 from database ..ListView 2 is with id=2 and so on. When I click on item 2 to open that ID from DB. Any idea how can I do this?
This is xml which load the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/buttons"
android:layout_marginTop="10dp"
>
<ImageView
android:id="#+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
/>
<TextView
android:id="#+id/name"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:text="" />
</LinearLayout>
</LinearLayout>
This is the part of code which I believe I need to fix
public class Restaurants extends Activity {
ListView listView;
TextView textView, textView1;
private StockAdaptor stockAdaptor;
String jsonResult = null;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants); //Just a listView, shown below
listView = (ListView) findViewById(android.R.id.list);
textView = (TextView) findViewById(R.id.name);
image = (ImageView) findViewById(R.id.image);
new JsonReadTask().execute("http://link/GetRestaurants.php");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(listView.getLayoutParams());
lp.setMargins(10, 10, 0, 0);
listView.setLayoutParams(lp);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Restaurants.this, RestaurantInformation.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true; //No options
}
public void onStart() {
super.onStart();
stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
}
public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
StringBuilder out = new StringBuilder();
BufferedReader breader = new BufferedReader(new InputStreamReader(in));
String cline;
String newLine = System.getProperty("line.separator");
while ((cline = breader.readLine()) != null) {
out.append(cline);
out.append(newLine);
}
return out.toString();
}
private class StockAdaptor extends BaseAdapter { //The stocks list adaptor
class ViewHolder {
TextView name;
//TextView menu;
ImageView image;
}
private LayoutInflater layoutInflater;
private RestaurantStrings[] stocks = null; //Array of stocks
private ListView stocksListView = null;
public StockAdaptor(Context context) {
super();
layoutInflater = LayoutInflater.from(context);
}
public void setStockList(RestaurantStrings[] stocksinfo) {
this.stocks = stocksinfo;// //////////////LITERALLY THIS
}
#Override
public int getCount() {
return stocks.length;
}
#Override
public Object getItem(int position) {
return stocks[position];
}
public RestaurantStrings[] getAll() { //Return the array of stocks
return stocks;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder; //New holder
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.restaurant_second, null);
holder = new ViewHolder();
// Creates the new viewHolder define above, storing references to the children
holder.name = (TextView) convertView.findViewById(R.id.name);
//holder.menu = (TextView) convertView.findViewById(R.id.menu);
holder.image = (ImageView) convertView.findViewById(R.id.image);
if (holder.image != null) {
if (holder.image.getDrawable() == null) {
new ImageDownloaderTask(holder.image, null)
.execute(stocks[position].image); //Download the image using the image
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(stocks[position].name);
//holder.menu.setText(stocks[position].menu);
return convertView;
}
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (URLUtil.isValidUrl(params[0])) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(getRequest);
final HttpEntity httpentity = response.getEntity();
if (httpentity != null){
InputStream inputStream = null;
try {
inputStream = httpentity.getContent();
jsonResult = strFromStream(inputStream);
Log.i("", jsonResult);
return jsonResult;
} catch (IllegalArgumentException e) {
//
} finally {
httpentity.consumeContent();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.close();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
// build hash set for list view
public void ListDrwaer() {
//Log.d("data from server", "data: " + jsonResult.toString());
try {
if (jsonResult!=null) {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
Vector<RestaurantStrings> vstocks = new Vector<RestaurantStrings>();
if(jsonMainNode == null)
{
Log.e("If is null", "jsonMainNode is null");
return;
}
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantStrings stock = new RestaurantStrings();
stock.image = jsonChildNode.getString("image");
stock.name = jsonChildNode.optString("name");
//stock.menu = jsonChildNode.optString("menu");
//stock.imgPath = jsonChildNode.getString("imgPath");
Log.e("err", stock.image + " " + stock.name);
vstocks.add(stock);
}
RestaurantStrings[] stocks = new RestaurantStrings[jsonMainNode.length()];
int stockscount = jsonMainNode.length();
for (int n = 0; n < stockscount; n++)
{
stocks[n] = vstocks.get(n);
}
stockAdaptor.setStockList(stocks);
listView.setAdapter(stockAdaptor);
} else {
Toast.makeText(getApplicationContext(), "Error; jsonResult null",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView, View view) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//
}
}
}
}
Bitmap downloadBitmap(String url) {
if(URLUtil.isValidUrl(url)){
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
try {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
}
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
return null;
}
}
}
If I try to put in onCreate() one setOnClickListener as you can see the app gives "Unfortunately your app has stopped"
UPDATE
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity"
android:background="#D3D3D3">
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
/>
<ListView
android:id="#id/android:list"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/image"
android:layout_alignParentTop="true"
android:divider="#android:color/transparent"
android:dividerHeight="5dp" >
</ListView>
</RelativeLayout>
Error
11-05 13:37:26.498: E/AndroidRuntime(1493): FATAL EXCEPTION: main
11-05 13:37:26.498: E/AndroidRuntime(1493): Process: com.reserveme, PID: 1493
11-05 13:37:26.498: E/AndroidRuntime(1493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.reserveme/com.reserveme.Restaurants}: java.lang.NullPointerException
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.access$800(ActivityThread.java:135)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.os.Handler.dispatchMessage(Handler.java:102)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.os.Looper.loop(Looper.java:136)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.main(ActivityThread.java:5017)
11-05 13:37:26.498: E/AndroidRuntime(1493): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 13:37:26.498: E/AndroidRuntime(1493): at java.lang.reflect.Method.invoke(Method.java:515)
11-05 13:37:26.498: E/AndroidRuntime(1493): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-05 13:37:26.498: E/AndroidRuntime(1493): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-05 13:37:26.498: E/AndroidRuntime(1493): at dalvik.system.NativeStart.main(Native Method)
11-05 13:37:26.498: E/AndroidRuntime(1493): Caused by: java.lang.NullPointerException
11-05 13:37:26.498: E/AndroidRuntime(1493): at com.reserveme.Restaurants.onCreate(Restaurants.java:69)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.Activity.performCreate(Activity.java:5231)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-05 13:37:26.498: E/AndroidRuntime(1493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
11-05 13:37:26.498: E/AndroidRuntime(1493): ... 11 more
I am using a ListView in one of my projects too. To get the touched/clicked position in my listview I have registered a ClickHandler to the ListView (not to the items of the list).
In your example the ID is equal to the position, so I think you could do the same.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
Intent intent = new Intent(Restaurants.this, RestaurantInformation.class);
intent.putExtra("myID", position);
startActivity(intent);
}
});
In the new Activity you can call the following to get the id:
Intent intent = getIntent();
if (intent.getExtras() != null) {
myID = (Integer) intent.getExtras().get("myID");
}

Image doesn't show in ImageView

I've tried may be every solution from here but nothing helped me. The image doesn't show on the listview only the text. I got only this in LogCat
11-04 14:46:29.319: I/(1225): {"Restaurants":[{"id":"1","name":"Restaurant- 1","menu":"Restaurant-1","image":"rest1.jpg"},{"id":"2","name":"Restaurant-2","menu":"Restaurant-2","image":"rest2.jpg"},{"id":"3","name":"Restaurant-3","menu":"Restaurant-3","image":"rest3.jpg"},{"id":"4","name":"Restaurant-4","menu":"Restaurant-4","image":"rest4.jpg"}]}
11-04 14:46:29.329: E/err(1225): rest1.jpg Restaurant-1 Restaurant-1
11-04 14:46:29.329: E/err(1225): rest2.jpg Restaurant-2 Restaurant-2
11-04 14:46:29.329: E/err(1225): rest3.jpg Restaurant-3 Restaurant-3
11-04 14:46:29.329: E/err(1225): rest4.jpg Restaurant-4 Restaurant-4
This is the code
public class Restaurants extends Activity {
ListView listView;
private StockAdaptor stockAdaptor;
String jsonResult = null;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurants);
listView = (ListView) findViewById(android.R.id.list);
image = (ImageView) findViewById(R.id.image);
new JsonReadTask().execute("http://link/GetRestaurants.php");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true; //No options
}
public void onStart() {
super.onStart();
stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
}
public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
StringBuilder out = new StringBuilder();
BufferedReader breader = new BufferedReader(new InputStreamReader(in));
String cline;
String newLine = System.getProperty("line.separator");
while ((cline = breader.readLine()) != null) {
out.append(cline);
out.append(newLine);
}
return out.toString();
}
private class StockAdaptor extends BaseAdapter { //The stocks list adaptor
class ViewHolder {
TextView name;
TextView menu;
ImageView image;
}
private LayoutInflater layoutInflater;
private RestaurantInformation[] stocks = null; //Array of stocks
private ListView stocksListView = null;
public StockAdaptor(Context context) {
super();
layoutInflater = LayoutInflater.from(context);
}
public void setStockList(RestaurantInformation[] stocksinfo) {
this.stocks = stocksinfo;
}
#Override
public int getCount() {
return stocks.length;
}
#Override
public Object getItem(int position) {
return stocks[position];
}
public RestaurantInformation[] getAll() { //Return the array of stocks
return stocks;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder; //New holder
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.restaurant_information, null);
holder = new ViewHolder();
// Creates the new viewHolder define above, storing references to the children
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.menu = (TextView) convertView.findViewById(R.id.menu);
holder.image = (ImageView) convertView.findViewById(R.id.image);
if (holder.image != null) {
if (holder.image.getDrawable() == null) {
new ImageDownloaderTask(holder.image, null)
.execute(stocks[position].image); //Download the image using the image
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(stocks[position].name);
holder.menu.setText(stocks[position].menu);
return convertView;
}
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (URLUtil.isValidUrl(params[0])) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(getRequest);
final HttpEntity httpentity = response.getEntity();
if (httpentity != null){
InputStream inputStream = null;
try {
inputStream = httpentity.getContent();
jsonResult = strFromStream(inputStream);
Log.i("", jsonResult);
return jsonResult;
} catch (IllegalArgumentException e) {
//
} finally {
httpentity.consumeContent();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.close();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
// build hash set for list view
public void ListDrwaer() {
//Log.d("data from server", "data: " + jsonResult.toString());
try {
if (jsonResult!=null) {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("Restaurants");
Vector<RestaurantInformation> vstocks = new Vector<RestaurantInformation>();
if(jsonMainNode == null)
{
Log.e("If is null", "jsonMainNode is null");
return;
}
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
RestaurantInformation stock = new RestaurantInformation();
stock.image = jsonChildNode.getString("image");
stock.name = jsonChildNode.optString("name");
stock.menu = jsonChildNode.optString("menu");
//stock.imgPath = jsonChildNode.getString("imgPath");
Log.e("err", stock.image + " " + stock.name + " " + stock.menu);
vstocks.add(stock);
}
RestaurantInformation[] stocks = new RestaurantInformation[jsonMainNode.length()];
int stockscount = jsonMainNode.length();
for (int n = 0; n < stockscount; n++)
{
stocks[n] = vstocks.get(n);
}
stockAdaptor.setStockList(stocks);
listView.setAdapter(stockAdaptor);
} else {
Toast.makeText(getApplicationContext(), "Error; jsonResult null",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView, View view) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return downloadBitmap(params[0]);
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//
}
}
}
}
Bitmap downloadBitmap(String url) {
if(URLUtil.isValidUrl(url)){
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
try {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
}
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
return null;
}
}
}
I'm not so experienced in Java+Android and really have no idea what can be the problem.
This is the restaurants.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Activity" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp" />
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignLeft="#+id/image"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
UPDATE
The goal is something like this. I want to load image on the left side and next to it to have text and sub-text if is possible
UPDATE restaurant_information.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="3dp"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="" />
<TextView
android:id="#+id/menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="" />
</LinearLayout>
Your ListView is defined as layout_width="fill_parent" and layout_height="fill_parent". As such, it will take up the entire area of it's parent and since it is defined last in the layout, will be at the top of the z-order thereby obscuring your ImageView.
Give this a try:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Activity" >
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
<ListView
android:id="#id/android:list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/image"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
You're trying to download the picture from: "rest1.jpg". You need a complete URL.
You can either send the complete url inside the json response, or add it inside your code (if the part that comes before the filename is fixed)

my activity work fine on 4.0 not work on 4.2

My activity does not work on Android 4.1, but it works fine on 2.2, 2.3, and 4.0. Some error show in the logcat I pasted below.
What is happening?
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
ImageButton slideHandleButton;
String name;
String name2;
long Menu_ID;
String dish_name;
String Type;
String status;
String message;
// HorizontalListView listview;
// CategoryListAdapter3 cla;
String DescriptionAPI;
// ImageLoader2 imgLoader;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
static ArrayList < Long > Category_ID = new ArrayList < Long > ();
static ArrayList < String > Category_name = new ArrayList < String > ();
static ArrayList < String > Category_image = new ArrayList < String > ();
public static String allergen2;
// private AQuery androidAQuery;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
// txt2 = (TextView) findViewById(R.id.test_button_text1);
txt3 = (TextView) findViewById(R.id.description);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
// androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this, LinkButtons.class); startActivity(iMenuList);}});
dish_name = iGet.getStringExtra("dish_name");
ImageView btnback = (ImageView) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
finish();}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
// SelectMenuAPI = Utils.dishdescription;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
// URL2 = SelectMenuAPI;
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
String[]mVal = new String[school2.length()];
for (int i = 0; i < school2.length(); i++) {
String name = school2.getJSONObject(0).getString("name");
txt1.setText(name);
String description = school2.getJSONObject(0).getString("description");
txt3.setText(description);
String url1 = school2.getJSONObject(0).getString("image");
androidAQuery.id(img1).image(url1, false, false);
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
final View row = createRow(school3.getJSONObject(s));
table.addView(row);
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
listview.setAdapter(cla);
}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
JSONObject jsonObject = school5.getJSONObject(i);
final View row2 = createRow2(school5.getJSONObject(i));
table3.addView(row2);
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch(JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item.getString("name"));
return row;
} public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item.getString("sub_ingredients"));
return row2;
}}
Logcat:
Skipped 74 frames! The application may be doing too much work on its main thread.
Skipped 61 frames! The application may be doing too much work on its main thread.
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x40a71930)
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.schoollunchapp/com.schoollunchapp.fifthscreen}:
android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection
(DefaultClientConnectionOperator.java:144)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.schoollunchapp.fifthscreen.parseJSONData(fifthscreen.java:196)
at com.schoollunchapp.fifthscreen.onCreate(fifthscreen.java:157)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
All network related operations are not to be run in the UI thread. This must be causing the issue. For more details.
http://developer.android.com/training/basics/network-ops/connecting.html
It happens because of absence of AsyncTask. Put all HttpClient logic to AsyncTask.
From your logs:
android.os.NetworkOnMainThreadException
You can't run parseJSONData on main Thread.
Here is some example how to implement it:
private class AsyncRequestConnection extends AsyncTask<Void, Void, String> {
private final Request request;
public AsyncRequestConnection(Request request) {
this.request = request;
}
#Override
protected String doInBackground(Void... params) {
try {
HttpPost p = createRequestHttpMessage(request);
String resp = new String(stripResponse(getRequestClient().execute(p)));
Log.v(TAG, resp);
return resp;
} catch (Exception e) {
Log.e(TAG, "Cannot complete API request", e);
cancel(false);
return null;
}
}
#Override
protected void onCancelled() {
request.backoff();
if (request.hasReachedMaxBackoff()) {
request.cancel(R.string.error_internal);
} else {
requestQueue.enqueue(request);
}
requestConnection = null;
nextRequest();
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
request.attachResponse(result);
request.handleResponse();
requestConnection = null;
nextRequest();
} else {
request.cancel(R.string.error_internal);
}
}
}
From your Activity just call it:
AsyncRequestConnection task = new AsyncRequestConnection ();
task.execute();

Categories

Resources