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
}
Related
I hope someone out there can help me solve my problem. I have android app that have 3 tabs, i use fragment, first tab is recyclerView list, second tabs is map. the problem is in tabs 1, i need to fetch data with volley to recyclerView on tabs 1, if run fine but i cannot see the data on first app start, but when i change tab and back to tab 1 again it will refresh the data and show the data on recyclerView.
Adapter.java
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Warkop> mWarkop;
private LayoutInflater inflater;
public CustomListAdapterWarkop(Context context, List<Warkop> mWarkop) {
this.context=context;
inflater= LayoutInflater.from(context);
this.mWarkop = mWarkop;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_warkop_row, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
Warkop current = mWarkop.get(position);
viewHolder.tvNamaWarkop.setText(current.getNamaWarkop());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.showImageOnLoading(R.drawable.noimage).build();
imageLoader.displayImage(current.getFotoWarkop(), viewHolder.ivFotoWarkop, options);
}
#Override
public int getItemCount() {
return mWarkop.size();
}
}
ItemHolder.java
package com.andylah.warkopedia;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by andylah on 11/3/2017.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public ImageView ivFotoWarkop;
public TextView tvNamaWarkop;
public ItemViewHolder(View itemView) {
super(itemView);
tvNamaWarkop = itemView.findViewById(R.id.nama_warkop);
ivFotoWarkop = itemView.findViewById(R.id.image_warkop);
}
}
Tab 1.java
public class tabSatu extends Fragment {
private static final String TAG = tabDua.class.getSimpleName();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private boolean isFragmentLoaded = false;
View vTabSatu;
private RecyclerView recyclerView;
public static List<Warkop> warkopList = new ArrayList<Warkop>();
private CustomListAdapterWarkop warkopAdapter;
public tabSatu(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new AsyncFetch().execute();
vTabSatu = inflater.inflate(R.layout.tabsatu_view, container, false);
recyclerView = vTabSatu.findViewById(R.id.warkop_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Log.d("LOG : ", "onCreatedView Run");
// Inflate the layout for this fragment
return vTabSatu;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
Log.d("LOG : ", "onViewCreated Run");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded ) {
// Load your data here or do network operations here
isFragmentLoaded = true;
//new AsyncFetch().execute();
}else{
isFragmentLoaded = false;
Log.d("LOG : ", "isFragmentLoaded = false");
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading list warkop ...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(AppConfig.LOAD_WARKOP);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try{
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if(!error){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
warkop.setNamaWarkop(jsonObject.getString("nama_warkop"));
warkop.setAlamatWrkop(jsonObject.getString("alamat_warkop"));
warkop.setKotaWarkop(jsonObject.getString("kota_warkop"));
warkop.setLatWarkop(Double.parseDouble(jsonObject.getString("lat_warkop")));
warkop.setLangWarkop(Double.parseDouble(jsonObject.getString("long_warkop")));
warkop.setIsWifi(Integer.parseInt(jsonObject.getString("is_wifi")));
warkop.setIsToilet(Integer.parseInt(jsonObject.getString("is_toilet")));
warkop.setIsTv(Integer.parseInt(jsonObject.getString("is_tv")));
warkop.setIsColokan(Integer.parseInt(jsonObject.getString("is_colokan")));
warkop.setIsParkir(Integer.parseInt(jsonObject.getString("is_parkir")));
warkop.setFotoWarkop(jsonObject.getString("foto_warkop"));
warkopList.add(warkop);
}
}else{
String errorMsg = object.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Problem: Even you call notifyDataSetChanged() but there are no data in Adapter.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
}
So you need to set and notify warkopList to Adapter after API call. It will help you.
tabSatu:
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try {
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if (!error) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
...
warkopList.add(warkop);
adapter.setItems(warkopList);
}
}
...
}
CustomListAdapterWarkop: add setItem() method to Adapter
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
public void setItems(List<WarkopList> warkopList) {
mWarkop = warkopList;
notifyDataSetChanged();
}
...
}
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 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 have a button that loads a new fragment but it is force closing with this error:
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.BPTopTastes.onCreateView(BPTopTastes.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
the button that loads the new fragment is this:
public class Discover extends Fragment {
Fragment Fragment_one;
Fragment Fragment_two;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_discover, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//add button onclick fo top beers
Button bt = (Button)v.findViewById(R.id.discoverBeers);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do whatever stuff you wanna do here
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_one=new BPTopBeers();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
//todo: add button onclick fo top tastes
Button bt2 = (Button)v.findViewById(R.id.discoverTaste);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do whatever stuff you wanna do here
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_two=new BPTopTastes();
tran.replace(R.id.main, Fragment_two);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
// Inflate the layout for this fragment
//todo: change to discover layout
return v;
}
the fragment that is being launched is:
public class BPTopTastes extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.taste_statistics_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String title = "Top Tastes on Beer Portfolio";
TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);
topTitle.setText(title);
//construct url
String url = "myURL";
//async task goes here
new GetTasteStatisticsJSON(getActivity()).execute(url);
// Inflate the layout for this fragment
return v;
}
}
and the async task which is being called is:
public class GetTasteStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetTasteStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting tastes");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourTasteStatistics);
//make array list for beer
final List<TasteInfo> tasteList = new ArrayList<TasteInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String style = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
int count = i + 1;
style = count + ". " + style;
Log.d("brewery stats", style);
//create object
TasteInfo tempTaste = new TasteInfo(style, rate);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
TasteInfoAdapter adapter1 = new TasteInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
TasteInfo o=(TasteInfo)arg0.getItemAtPosition(arg2);
String tempTaste = o.taste;
//todo: load taste page fragment
//Intent myIntent = new Intent(c, TastePage.class);
// myIntent.putExtra("taste", tempTaste);
//c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
I am a bit confused cause I have another button in the same fragment that launches a new fragment in a similar way just fine...
I just noticed my mistake after combing through my code. I have the wrong id here in this line:
TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);
so it could not find that, to set the title.
Can you check the BPTopTastes layout is inflating correctly, and hence topTitle is not null when you call the setText() method on it.
Does it work when you remove the async task ?
The Eclipse debugger can be set to halt on exception which might give you some pointers.
I am writing an App in which i am trying to fetch previous Order Details from Server PHPMYADMIN, and want to show these order details in ListView, but whenever i run my app getting NullPointerException, please check my code and tell me what i am missing and where i am doing mistake..
Log says:
05-22 12:33:35.652: E/AndroidRuntime(786): Caused by: java.lang.NullPointerException
05-22 12:33:35.652: E/AndroidRuntime(786): at OrdersActivity.showInfo(OrdersActivity.java:121)
05-22 12:33:35.652: E/AndroidRuntime(786): at OrdersActivity.onCreate(OrdersActivity.java:75)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.Activity.performCreate(Activity.java:5104)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-22 12:33:35.652: E/AndroidRuntime(786): ... 11 more
Error Line Number 75 is : showinfo();
Error Line Number 121 is : if(!strMemberID.equals(""))
OrdersActivity.java:
public class OrdersActivity extends Activity {
TextView total, items ;
String strMemberID,resultServer,MemberID;
ListView list;
OrdersAdapter adapter;
ArrayList<HashMap<String, String>> itemsList;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
showInfo();
itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(this, itemsList);
list.setAdapter(adapter);
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdersActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
public void showInfo()
{
total = (TextView)findViewById(R.id.txtTotalAmount);
items = (TextView)findViewById(R.id.txtItemDetails);
String url = "http://172.16.0.4/res/order_fetch.php";
Intent intent= getIntent();
MemberID = intent.getStringExtra("MemberID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMemberID", MemberID));
resultServer = getHttpPost(url,params);
String strTotal = "";
String strItems = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strTotal = c.getString("TotalAmount");
strItems = c.getString("ItemDetails");
if(!strMemberID.equals(""))
{
total.setText(strTotal);
items.setText(strItems);
}
else
{
total.setText("-");
items.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
OrdersActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(OrdersActivity.this, itemsList);
list.setAdapter(adapter);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
}
OrdersAdapter.java:
public class OrdersAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
String strName,strMemberID ;
public OrdersAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listrow_orders, null);
TextView title = (TextView)vi.findViewById(R.id.txtTotalAmount);
TextView description = (TextView)vi.findViewById(R.id.txtItemDetails);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(strName));
description.setText(strMemberID);
return vi;
}
}
Declare your strMemberID as String strMemberID = "";
NullPointorException will be solved... :)
The default initialization for the String type, when it is declared in the Class scope, is null. That's mean that you can not use before intialize it. You can change the if this way:
if(strMemberID != null && !strMemberID.equals("")) {
}