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");
}
Related
Hi i am getting data from server and storing in sqlite and showing inside swiping tabs which is dynamic.I get error some times and some times it works just fine. I am not getting why crash is occuring. I tried to debug but could not find the issue.Need help to resolve this issue.
Here the async task code.
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> implements
OnClickListener {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
// ------------------>>
URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type",
"application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(
urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
JSONObject jsono = new JSONObject(response);
JSONArray jarray = jsono.getJSONArray("product");
for (int i = 0; i < jarray.length(); i++) {
JSONObject feedObj = jarray.getJSONObject(i);
// Actors actor = new Actors();
CartItem item = new CartItem();
item.setQuantity("0");
item.setProductName(feedObj.optString("post_title"));
item.setPrice(feedObj.optString("post_excerpt"));
item.setProductPrice(feedObj.optString("meta_value"));
item.setProductId(ids);
item.setProdId(feedObj.optString("ID"));
item.setProductTotalPrice("0");
item.setImage(feedObj.optString("image_url"));
mHelper.addProduct(item);
System.out.println("Database price : "+item.getProductPrice());
}
return true;
}
// ------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result == false) {
recyclerView.setVisibility(View.GONE);
fhfgh.setVisibility(View.VISIBLE);
} else {
listAdapter = new FeedListAdapter(getActivity(), mHelper.getAllProducts(ids));// Error on this line.
recyclerView.setAdapter(listAdapter);
listAdapter.setOnAddNum(this);
listAdapter.setOnSubNum(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(
getActivity()));
}
}
Here is the logcat
05-20 12:08:26.308: E/AndroidRuntime(8564): FATAL EXCEPTION: main
05-20 12:08:26.308: E/AndroidRuntime(8564): java.lang.NullPointerException
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.grotap.adapter.FeedListAdapter.<init>(FeedListAdapter.java:47)
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.grotap.activity.MyFragment$JSONAsyncTask.onPostExecute(MyFragment.java:350)
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.grotap.activity.MyFragment$JSONAsyncTask.onPostExecute(MyFragment.java:1)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.AsyncTask.finish(AsyncTask.java:631)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.Looper.loop(Looper.java:137)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.app.ActivityThread.main(ActivityThread.java:5283)
05-20 12:08:26.308: E/AndroidRuntime(8564): at java.lang.reflect.Method.invokeNative(Native Method)
05-20 12:08:26.308: E/AndroidRuntime(8564): at java.lang.reflect.Method.invoke(Method.java:511)
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
05-20 12:08:26.308: E/AndroidRuntime(8564): at dalvik.system.NativeStart.main(Native Method)
Here is the adapter class
public class FeedListAdapter extends
RecyclerView.Adapter<FeedListAdapter.ViewHolder> {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<CartItem> feedItems;
private ArrayList<CartItem> filteredfeedItems;
ImageView plus;
ImageView minus;
String result;
String formattedDate;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int id;
private TextView prices;
private View.OnClickListener onAddNum;
private View.OnClickListener onSubNum;
public FeedListAdapter(Activity activity, ArrayList<CartItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
this.filteredfeedItems = feedItems;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setOnAddNum(View.OnClickListener onAddNum) {
this.onAddNum = onAddNum;
}
public void setOnSubNum(View.OnClickListener onSubNum) {
this.onSubNum = onSubNum;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.feed_item, parent, false);
prices = (TextView) v.findViewById(R.id.timestamp2);
ViewHolder viewHolder = new ViewHolder(v);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
// setupClickableViews(v, viewHolder);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
CartItem item = (CartItem) filteredfeedItems.get(position);
holder.name.setText(item.getProductName());
holder.assignTo.setText(item.getPrice());
String rupee = activity.getResources().getString(R.string.Rs);
holder.price.setText(rupee+" "+item.getProductPrice());
holder.location.setText((String.valueOf(item.getQuantity())) + "");
holder.plus.setTag(item.getId());
holder.plus.setFocusable(true);
holder.plus.setClickable(true);
holder.plus.setOnClickListener(onAddNum);
holder.minus.setTag(item.getId());
holder.minus.setOnClickListener(onSubNum);
holder.profilePic.setImageUrl(item.getImage(), imageLoader);
holder.profilePic.setDefaultImageResId(R.mipmap.ic_launcher);
holder.profilePic.setErrorImageResId(R.mipmap.ic_launcher);
//Picasso.with(activity).load(item.getImage()).into(holder.profilePic);
}
/*private void displayImage(int adapterPosition) {
// TODO Auto-generated method stub
LayoutInflater inflater = activity.getLayoutInflater();
View offer = inflater.inflate(R.layout.prompts, null);
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setView(offer);
alert.setCancelable(true);
final AlertDialog dialog = alert.create();
int width = (int)(activity.getResources().getDisplayMetrics().widthPixels*0.80);
int height = (int)(activity.getResources().getDisplayMetrics().heightPixels*0.50);
dialog.show();
dialog.getWindow().setLayout(width, height);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
CartItem item = (CartItem) filteredfeedItems.get(adapterPosition);
NetworkImageView viewOffer = (NetworkImageView)offer.findViewById(R.id.viewOffer);
viewOffer.setImageUrl(item.getImage(),imageLoader);
viewOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}*/
#Override
public int getItemCount() {
return filteredfeedItems.size();
}
public long getItemId(int position) {
return position;
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView plus;
ImageView minus;
NetworkImageView profilePic;
TextView name;
TextView price;
TextView assignTo;
TextView location;
public ViewHolder(View vi) {
super(vi);
name = (TextView) vi.findViewById(R.id.name);
price = (TextView) vi.findViewById(R.id.price);
assignTo = (TextView) vi.findViewById(R.id.timestamp);
location = (TextView) vi.findViewById(R.id.timestamp2);
plus = (ImageView) vi.findViewById(R.id.btnAddToCart1);
profilePic = (NetworkImageView) vi.findViewById(R.id.profilePic);
minus = (ImageView) vi.findViewById(R.id.btnAddToCart5);
}
}
}
Here is getAllProducts
public ArrayList<CartItem> getAllProducts(String ids) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<CartItem> cityList = null;
try{
cityList = new ArrayList<CartItem>();
String QUERY = "SELECT * FROM "+TABLE_NAME+ " WHERE " +KEY_PRODUCT_ID
+ " = '" + ids + "'";
Cursor cursor = db.rawQuery(QUERY, null);
if(!cursor.isLast())
{
while (cursor.moveToNext())
{
CartItem city = new CartItem();
city.setId(cursor.getInt(0));
city.setQuantity(cursor.getString(1));
city.setProductName(cursor.getString(2));
city.setPrice(cursor.getString(3));
city.setProductPrice(cursor.getString(4));
city.setProductId(cursor.getString(5));
city.setProductTotalPrice(cursor.getString(6));
city.setImage(cursor.getString(7));
city.setProdId(cursor.getString(8));
cityList.add(city);
}
}
db.close();
}catch (Exception e){
Log.e("error",e+"");
}
return cityList;
}
In your onPostExecute() method, you make a call to getActivity(). This method returns null, because your fragment is not yet attached to an activity. Make sure that the call to getActivity() is made only after onAttach() is called on your fragment.
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();
I have application, that get images by address "http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png"(for example) from server
public class MenuActivity extends Activity {
private static ArrayList<Products> myProducts;
ParseJSON parseJSON;
private static ArrayList <Bitmap> bm;
final String GetMenuUrl = "http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/get_menu.php";
String City = "Moscow";
String NameCinema = "Avrora";
private ProgressDialog dialog;
private String response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
init();
new RequestTask().execute(GetMenuUrl);
}
private void init(){
myProducts = new ArrayList<Products>();
parseJSON = new ParseJSON();
}
private void setAdapter(ArrayList<Products> products){
GridView grid;
for(int i = 0; i < myProducts.size(); i++){
try {
bm.add(downloadBitmap("http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("size == " + bm.size());
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
SetImg("http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png",imageView);
System.out.println("size == " + bm.size());
CustomGrid adapter = new CustomGrid(MenuActivity.this, products, bm);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MenuActivity.this, "Продукт " + myProducts.get(position).getProductName() + " добавлен в корзину", Toast.LENGTH_SHORT).show();
}
});
}
private void SetImg(final String url,final ImageView v){
final ProgressDialog dialog = ProgressDialog.show(this, "Download",
"downloading");
dialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap downloadBitma = downloadBitmap(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
v.setImageBitmap(downloadBitma);
}
});
} catch (IOException e) {
e.printStackTrace();
} finally {
dialog.dismiss();
}
}
}).start();
}
private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
DefaultHttpClient hc = new DefaultHttpClient();
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(params[0]);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("city", City));
nameValuePairs.add(new BasicNameValuePair("name_cinema",NameCinema));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = hc.execute(postMethod, res);
parseJSON.parse(response.toString());
Log.d("response == ", response.toString());
myProducts = parseJSON.getObjects();
Log.d("firstProduc == ", myProducts.get(0).getProductName());
} catch (Exception e) {
System.out.println("Exp=" + e);
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
ArrayList<String> products = new ArrayList<String>();
for(int i = 0 ; i < myProducts.size(); i++){
products.add(myProducts.get(i).getProductName());
}
if(products.size() != 0)
setAdapter(myProducts);
else Log.d("error", "can`t load");
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MenuActivity.this);
dialog.setMessage("Загружаюсь...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
super.onPreExecute();
}
}
}
//display images to gridview
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final ArrayList<Products> web;
private final ArrayList<Bitmap> Imageid;
public CustomGrid(Context c,ArrayList<Products> web,ArrayList<Bitmap>Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return web.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.rowlayout, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
TextView textDescr = (TextView) grid.findViewById(R.id.grid_description);
final ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(web.get(position).getProductName());
textDescr.setText(String.valueOf(web.get(position).getProductPrice()) + "руб.");
// imageView.setImageResource(Imageid[position]);
imageView.setImageBitmap(Imageid.get(position));
} else {
grid = (View) convertView;
}
return grid;
}
}
But I have errors:
10-30 09:27:23.081 2820-2820/com.example.kinofood E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
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.example.kinofood.MenuActivity.downloadBitmap(MenuActivity.java:162)
at com.example.kinofood.MenuActivity.setAdapter(MenuActivity.java:79)
at com.example.kinofood.MenuActivity.access$400(MenuActivity.java:38)
at com.example.kinofood.MenuActivity$RequestTask.onPostExecute(MenuActivity.java:232)
at com.example.kinofood.MenuActivity$RequestTask.onPostExecute(MenuActivity.java:186)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
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)
how can I change my code? thank you
You can't download on MainThread. If You want to do this Your way, You will have to load it asynchronously, i.e. using AsyncTask.
But the best way to load online images into ImageViews is use of 3rd party libraries.
Libraries known to me:
Universal Image Loader - https://github.com/nostra13/Android-Universal-Image-Loader
Picasso - http://square.github.io/picasso/
Besides simply loading images they handle for You caching, animations, event handling etc.
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)
I want use universal image loader(UIL) to display images whose urls are stored in the mysql database. The demo of UIL with constants class works well. However, some errors occurs after a little modification for my own purpose.
The error information are :
03-12 13:56:13.375: E/AndroidRuntime(31634): FATAL EXCEPTION: main
03-12 13:56:13.375: E/AndroidRuntime(31634): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.ImageGridActivity}: java.lang.NullPointerException
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.os.Handler.dispatchMessage(Handler.java:99)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.os.Looper.loop(Looper.java:130)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.ActivityThread.main(ActivityThread.java:3835)
03-12 13:56:13.375: E/AndroidRuntime(31634): at java.lang.reflect.Method.invokeNative(Native Method)
03-12 13:56:13.375: E/AndroidRuntime(31634): at java.lang.reflect.Method.invoke(Method.java:507)
03-12 13:56:13.375: E/AndroidRuntime(31634): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
03-12 13:56:13.375: E/AndroidRuntime(31634): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
03-12 13:56:13.375: E/AndroidRuntime(31634): at dalvik.system.NativeStart.main(Native Method)
03-12 13:56:13.375: E/AndroidRuntime(31634): Caused by: java.lang.NullPointerException
03-12 13:56:13.375: E/AndroidRuntime(31634): at com.example.test.ImageGridActivity.onCreate(ImageGridActivity.java:45)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-12 13:56:13.375: E/AndroidRuntime(31634): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
03-12 13:56:13.375: E/AndroidRuntime(31634): ... 11 more
Firstly, the ImageGridView.java is:
public class ImageGridActivity extends AbsListViewBaseActivity {
String[] imageUrls;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
initView();
// Retrieval data from the intent
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Commons.IMGURLS); ----> Line 45
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.gridView1);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}
private void initView() {
String url = "http://192.168.2.200/test/app.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
//public class ImageAdapter extends BaseAdapter {
public class ImageAdapter extends BaseAdapter {
public int getCount() {
Log.d("hui", "getcount = " + Integer.toString(imageUrls.length));
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.item_image_grid, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.imageView1);
holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
view.setTag(holder);
} else {
holder = (ViewHolder)view.getTag();
}
imageLoader.displayImage(imageUrls[position],
holder.imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri,
View view) {
holder.progressBar.setProgress(0);
holder.progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri,
View view, FailReason failReason) {
holder.progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
holder.progressBar.setVisibility(View.GONE);
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri,
View view, int current, int total) {
holder.progressBar.setProgress(Math
.round(100.0f * current / total));
}
});
return view;
}
class ViewHolder {
ImageView imageView;
ProgressBar progressBar;
}
}
}
I have also implemented a fetchDataTask class which is the son of AsyncTask. The code is
public class FetchDataTask extends AsyncTask<String, Void, String> {
ArrayList<HashMap<String, String>>hashMaps;
ArrayList<String> urlArrayList;
String [] urlStrings;
String urlString;
Intent intent;
ProgressDialog loDialog;
private Context context;
JSONObject jsonObject;
JSONArray jsonArray;
public FetchDataTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
loDialog = new ProgressDialog(context);
loDialog.setMessage("Loading Images...");
loDialog.setIndeterminate(false);
loDialog.show();
}
#Override
protected String doInBackground(String... params) {
if (params == null)
return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
Log.i("hui", streamToString(is));
return streamToString(is);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
urlArrayList = new ArrayList<String>();
for (int i = 0; i < aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
HashMap<String, String> hash= new HashMap<String, String>();
hash.put("img_url", json.getString("img_url"));
hashMaps.add(hash);
urlString = json.getString("img_url");
urlArrayList.add(urlString);
urlStrings = urlArrayList.toArray(new String [urlArrayList.size()]);
}
intent = new Intent(context, ImageGridActivity.class);
intent.putExtra(Commons.IMGURLS, urlStrings);
context.startActivity(intent);
// notify the activity that fetch data has been complete
// if (listener != null)
// listener.onFetchComplete(imgfromServersList);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
throw e;
} finally {
try {
is.close();
} catch (IOException e) {
throw e;
}
}
return sb.toString();
}
///public class data
}
The some sample of Json data are like:
[{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/1.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/2.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/3.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/4.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/5.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/6.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/7.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/8.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/9.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/10.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/11.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/12.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/13.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/14.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/15.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/16.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/17.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/18.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/19.png"},{"img_url":"http:\/\/192.168.2.200\/test\/imgs\/20.png"}]
However, the code doesnt work, I don't know why.Any suggestions?
I guess your error is about how you tried to pass your string array between your android activites, for instance :
To pass data :
Bundle bundle = new Bundle();
bundle.putStringArray("tag", urlStrings);
Intent intend =new Intent(yourMainActivity.this, yourActivityToGetData.class);
intend.putExtras(bundle);
To read data :
Bundle bundle = this.getIntent().getExtras();
String[] array= bundle .getStringArray("tag");
In your ImageGridActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
initView();
FetchDataTask task = new FetchDataTask(ImageGridActivity.this);
task.execute(url);
...
And in your FetchDataTask :
#Override
protected void onPostExecute(String sJson) {
....
context.OnTaskCompleted(yourArray) // you just have to implement this method in ImageGridView activity
}