Getting error in onPostExecute of async task - android

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.

Related

App crashes if Internet is not available - Android

I am loading JSON from server but the app crashes if the internet is not available. How to fix this problem? I have added try catch in most part. Unable to find the problem. lvMovies.setAdapter(adapter); gives error when internet is not available. Code works fine when internet is available
public class JSONTest extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private ListView lvMovies;
private ProgressDialog dialog;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsontest);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeMovieHits);
swipeRefreshLayout.setOnRefreshListener(this);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView) findViewById(R.id.lvMovies);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
//new JSONTask().execute("http://ankushkapoor2016.16mb.com/ankush/myjson.txt");
//new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");
}
#Override
public void onRefresh() { //SwipeRefreshLayout Refresh Listener
try {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
} catch (Exception e) {
Toast.makeText(JSONTest.this, e.getMessage() + "\n\n" + e.getCause(), Toast.LENGTH_LONG).show();
}
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson1 = buffer.toString();
SharedPreferences sharedPreferences = getSharedPreferences("JSON_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("json", finalJson1);
editor.commit();
String finalJson=sharedPreferences.getString("json","N/A");
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float) finalObject.getDouble("rating"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setTagline(finalObject.getString("tagline"));
movieModel.setImage(finalObject.getString("image"));
movieModel.setStory(finalObject.getString("story"));
List<MovieModel.Cast> castList = new ArrayList<>();
for (int j = 0; j < finalObject.getJSONArray("cast").length(); j++) {
MovieModel.Cast cast = new MovieModel.Cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
movieModel.setCastList(castList);
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> s) {
super.onPostExecute(s);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, s);
lvMovies.setAdapter(adapter);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
}
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagline);
holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar;
progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
try {
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year: " + movieModelList.get(position).getYear());
holder.tvDuration.setText(movieModelList.get(position).getDuration());
holder.tvDirector.setText(movieModelList.get(position).getDirector());
holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);
StringBuffer stringBuffer = new StringBuffer();
for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText(stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage() + "\n" + e.getCause(), Toast.LENGTH_SHORT).show();
}
return convertView;
}
class ViewHolder {
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_json, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.jsonRefresh) {
try {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
return true;
} catch (Exception e) {
Toast.makeText(JSONTest.this, e.getMessage() + "\n\n" + e.getCause(), Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
}
To prevent crash you should check is device have internet connection, to do that you can use:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need to add to your AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you provide logcat message, then maybe I can tell you more about your problem.
Your problem is that you are returning a null arraylist when the internet exceptions are caught. So, the onPostExecute gets null, then the adapter gets null.
If you don't want a null value, pre-declare an empty list and always return it.
Then, the app won't crash, but you will see no data populate in the list, so you may want to do some additional validation that internet is available.
#Override
protected List<MovieModel> doInBackground(String... params) {
List<MovieModel> movieModelList = new ArrayList<>();
try {
// TODO: Stuff
return movieModelList;
} catch ( ... ) {
} finally {
}
return movieModelList;
}

Get image in gridview from server

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.

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");
}

How to display items in custom adapter android

Hi I need to store items in custom adapter but I got issue while creating custom adapter. Please help me to resolve.
private class Cast extends AsyncTask<Object, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(Detailed_View.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
private final String KeY = "";
private static final String DEBUG_TAG = "TM";
#Override
protected ArrayList<String> doInBackground(Object... params) {
try {
return getCast();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(ArrayList<String> results_Cast) {
updateListOfCast(results_Cast);
dialog.cancel();
};
public ArrayList<String> getCast() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("https://themovie/3/movie/" + id
+ "/credit");
stringBuilder.append("?key=" + key);
URL url = new URL(stringBuilder.toString());
// Log.d("urlstring",stringBuilder.toString() );
InputStream stream = null;
try {
// Establish a connection
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.addRequestProperty("Accept", "application/json"); // Required
// to
// get
// TMDB
// to
// play
// nicely.
conn.setDoInput(true);
conn.connect();
int responseCode = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response code is: " + responseCode + " "
+ conn.getResponseMessage());
stream = conn.getInputStream();
return parseCast(stringify(stream));
} finally {
if (stream != null) {
stream.close();
}
}
}
private ArrayList<String> parseCast(String result) {
String streamAsString = result;
ArrayList<String> results_Cast = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("cast");
Log.d("array view", array.toString());
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonMovieObject = array.getJSONObject(i);
results_Cast.add(jsonMovieObject.getString("name"));
ids=jsonMovieObject.getString("id");
results_Cast.add(jsonMovieObject.getString("character"));
}
} catch (JSONException e) {
Log.d("e", e.toString());
Log.d(DEBUG_TAG, "Error parsing JSON. String was: "
+ streamAsString);
}
// Log.d("resulted", results_Cast.toString());
return results_Cast;
}
public String stringify(InputStream stream) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
return bufferedReader.readLine();
}
}
// displays cast
public void updateListOfCast(ArrayList<String> result) {
ListView listView = (ListView) findViewById(R.id.cast_details);
//Log.d("updateViewWithResults", result.toString());
// Add results to listView.
listView.setAdapter(adapter);
Helper.getListViewSize(listView);
gridAdapter = new GridAdapter(this, R.layout.test_row, result); // here I have issue.
listView.setAdapter(gridAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idss) {
// TODO Auto-generated method stub
String name = (String) parent.getItemAtPosition(position);
Toast.makeText(Detailed_View.this, name+"Id"+ids, Toast.LENGTH_SHORT)
.show();
}
});
public class GridAdapter extends BaseAdapter {
public GridAdapter(Activity a, int resource, ArrayList<String> result) { // here it displays error as The blank final field itemLists may not have been initialized
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
results=result;
activity=a;
loader=new ImageLoader(a.getApplicationContext());
}
}
How to get items of name, id and character to display in custom adapter?
You have to overide all methods..
Example
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}

Use universal image loader and JSON rather than Constant Class

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
}

Categories

Resources