In my application i am loading data in a galleryview.If user clicks any item in galleryview i will load data from adapterclass.I kept an activity indicator between this loading and displaying data.But the activity indicator is not dismissing,it is showing continuously.
My activity code:
gal.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick (AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
// mDialog = new ProgressDialog(NewsPaperNov28MainGalleryActivity.this);
// mDialog.setMessage("Please wait...");
// mDialog.setCancelable(false);
mDialog= ProgressDialog.show(NewsPaperNov28MainGalleryActivity.this,"Working..", "Please Wait", true,false);
context.getInstance().setAppVariable("sectionurl", adapter.sectionurl[position]);
Thread thread = new Thread();
thread.start();
// ListView list=(ListView)findViewById(R.id.list);
// listadapter = new ListViewwithimageAdapter(this);
// list.setAdapter(listadapter);
}
});
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// TODO Auto-generated method stub
context.getInstance().setAppVariable("storyurl", listadapter.url[position]);
Intent in = new Intent(getApplicationContext(), NewsDescription.class);
startActivity(in);
}
});
}
#Override
public void run() {
// TODO Auto-generated method stub
// context.getInstance().setAppVariable("sectionurl", adapter.sectionurl[position]);
System.out.println("inside run");
list=(ListView)findViewById(R.id.list);
listadapter = new ListViewwithimageAdapter(this);
System.out.println("B4 handle");
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
System.out.println("Inside handler");
mDialog.dismiss();
list.setAdapter(listadapter);
}
};
My ListViewwithimageAdapter class:
public class ListViewwithimageAdapter extends BaseAdapter
{
private static Context contxt;
final String URL = "http://xxxxxxx/xml/stories/"+rgd.xml;
String[] kickerimage = {};//new String[50];
ListViewwithimageAdapter(Context conxt)
{
this.contxt=conxt;
getelement();
}
public ListViewwithimageAdapter(
OnItemSelectedListener onItemSelectedListener)
{
// TODO Auto-generated constructor stub
// this.contxt=conxt;
getelement();
}
public ListViewwithimageAdapter(OnItemClickListener onItemClickListener) {
// TODO Auto-generated constructor stub
getelement();
}
String[] itemsarray = {};//new String[100];
String[] url= {};//new String[30];
public String[] getelement()
{
// System.out.println("Insid getelement");
ArrayList<String> menuItems = new ArrayList<String>();
TaplistingParser parser = new TaplistingParser();
// System.out.println("url="+URL);
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
// System.out.println("sssss="+doc);
NodeList nl=doc.getElementsByTagName("article");
kickerimage = new String[nl.getLength()];
url = new String[nl.getLength()];
// String headings = null;
for(int i=0; i < nl.getLength(); i++)
{
// System.out.println("i="+i);
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// map.put("Title", parser.getValue(e, "title"));
// map.put("Date", parser.getValue(e, "create_date"));
url[i]=parser.getValue(e, "url");
// System.out.println("b4 kick");
// System.out.println("value="+parser.getValue(e, "title"));
kickerimage[i]=parser.getValue(e, "kickerimage");
// System.out.println("after kick");
// System.out.println("kick="+kickerimage[i]);
menuItems.add(parser.getValue(e, "title"));
}
// System.out.println("b4 items array");
itemsarray = new String[menuItems.size()];
// System.out.println("subbu");
itemsarray=menuItems.toArray(itemsarray);
// System.out.println("subbu1");
// System.out.println("in last");
return itemsarray;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return itemsarray.length;
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return itemsarray[position];
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
// System.out.println("pos in id="+position);
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
Bitmap bitmap = DownloadImage(
kickerimage[position] );
// View listView = convertView;
if (convertView == null)
{
//this should only ever run if you do not get a view back
LayoutInflater inflater = (LayoutInflater) contxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.homelistrow, null);
}
// else
// {
// holder.removeAllViews();
// }
// View listView;
// if (convertView == null)
// {
// listView = new View(contxt);
// LinearLayout holder = (LinearLayout)convertView.findViewById(android.R.id);
//// holder = inflater.inflate(R.layout.homelistrow, null);
// System.out.println("pos="+position);
// System.out.println("item="+getItem(position));
// else
// {
TextView textView = (TextView) convertView
.findViewById(R.id.name_label);
textView.setText(itemsarray[position]);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.icon);
imageView.setImageBitmap(bitmap);
// }
// else
// {
// listView = (View) convertView;
// }
// }
return convertView ;
}
private Bitmap DownloadImage(String URL)
{
// System.out.println("image inside="+URL);
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("image last");
return bitmap;
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
Where i am going wrong??Please help me thanks in advance..
I solved it ..the problem lies in the line
Thread thread = new Thread();
Instead of this i done:
Thread thread = new Thread(Myactivity.this);
Now the Indicator is disappearing after loading.Thanks to all..
Related
This is my code base adapter to set list item. My code in notifyDataSetChanged() not work. Delete Btn click to delete item of listview how can I change to work this code please help me
public class CustomListviewMyCartitem extends BaseAdapter {
ArrayList<Mycartitem> myList = new ArrayList<Mycartitem>();
LayoutInflater inflater;
Context context;
int loader = R.drawable.loader;
static int minteger = 0;
public String Response_code;
Mycartitem currentListData;
String cid, qcount;
UserSessionManager session;
String rem, b, userid, btntag;
public CustomListviewMyCartitem(Context context, ArrayList<Mycartitem> list) {
this.myList = list;
this.context = context;
inflater = LayoutInflater.from(context);
session = new UserSessionManager(context);
HashMap<String, String> user = session.getUserDetails();
userid = user.get(UserSessionManager.KEY_ID);
Log.e("", "#myList" + myList);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
/*
* public void updateReceiptsList() { myList.clear(); this.myList = list;
* this.notifyDataSetChanged(); }
*/
public void updateResults(ArrayList<Mycartitem> results) {
this.myList = results;
// Triggers the list update
this.notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.customcartlist, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
currentListData = myList.get(position);
mViewHolder.txtproductnamecart.setText(currentListData.getCategoryName());
mViewHolder.txtprizecart.setText("$" + currentListData.getCharge());
mViewHolder.txttotalitemcart.setText(currentListData.getQuantity());
mViewHolder.delete.setTag(currentListData.getCartItemId());
mViewHolder.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btntag = mViewHolder.delete.getTag() + "";
new DeleteItem().execute();
}
});
return convertView;
}
private class MyViewHolder {
TextView txtproductnamecart, txtprizecart, txttotalitemcart;
Button delete;
public MyViewHolder(View item) {
txtproductnamecart = (TextView) item.findViewById(R.id.txtproductnamecart);
txtprizecart = (TextView) item.findViewById(R.id.txtprizecart);
txttotalitemcart = (TextView) item.findViewById(R.id.txttotalitemcart);
delete = (Button) item.findViewById(R.id.btndelete);
}
}
private class DeleteItem extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
// Utils.Pdialog(Cart.this);
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
request();
return null;
}
protected void onPostExecute(Void unused) {
Utils.Pdialog_dismiss();
try {
JSONObject jsonObject;
jsonObject = new JSONObject(Response_code);
String msg = jsonObject.getString("status");
if (msg.equals("200")) {
JSONObject jsonArray = jsonObject.getJSONObject("payload");
updateResults(myList);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(context, "No item Found", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
private void request() {
try {
List<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("userId", userid));
values.add(new BasicNameValuePair("cartItemId", btntag));
values.add(new BasicNameValuePair("action", "singleItem"));
values.add(new BasicNameValuePair("cartId", Utils.CARTID));
Log.e("", "#Parameteruserid" + userid);
Log.e("", "#ParametercartItemId" + currentListData.getCartItemId());
Log.e("", "#Parameteaction" + "singleItem");
Log.e("", "#ParametercartId" + Utils.CARTID);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = Utils.link + "index.php/api/deletecartitem/";
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(values));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Response_code = client.execute(httppost, responseHandler);
Log.e("Cart item delete Response :---", "CratItemDelete" + Response_code);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Instead of the method:
public void updateResults(ArrayList<Mycartitem> results) {
this.myList = results;
// Triggers the list update
this.notifyDataSetChanged();
}
Use the following method:
public void updateResults(ArrayList<Mycartitem> results) {
this.myList.clear();
this.myList.addAll(results);
// Triggers the list update
this.notifyDataSetChanged();
}
you are not updating myList variable. clear all the items from list and update with new items and then call notifyDatasetchange.
I'm trying to parse a JSON result from a URL in my Android app.
I have tried a few examples on the Internet, but can't get it to work.
What's the simplest way to fetch the URL and parse the JSON data show it in the listview
Json data :
[{"MemberID":"1","Username":"weerachai","Password":"12345","Name":"Weerachai
Nukitram","Tel":"0819876107","Email":"weerachai#gmail.com"},{"MemberID":"2","Username":"adisorn","Password":"ac143","Name":"Adisorn
Bunsong","Tel":"021978032","Email":"adisorn#gmail.com"},{"MemberID":"3","Username":"surachai","Password":"gg111","Name":"Surachai
Sirisart","Tel":"0876543210","Email":"surachai#gmail.com"}]
Android code :
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> MyArrList;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ShowData();
// btnSearch
final Button btnSearch = (Button) findViewById(R.id.btnSearch);
//btnSearch.setBackgroundColor(Color.TRANSPARENT);
// Perform action on click
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ShowData();
}
});
}
public void ShowData()
{
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
// keySearch
EditText strKeySearch = (EditText)findViewById(R.id.txtKeySearch);
// Disbled Keyboard auto focus
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(strKeySearch.getWindowToken(), 0);
String url = "http:...............php";
// Paste Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtKeyword", strKeySearch.getText().toString()));
try {
JSONArray data = new JSONArray(getJSONUrl(url,params));
MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("MemberID", c.getString("MemberID"));
map.put("Username", c.getString("Username"));
map.put("Password", c.getString("Password"));
map.put("Name", c.getString("Name"));
map.put("Email", c.getString("Email"));
map.put("Tel", c.getString("Tel"));
MyArrList.add(map);
}
lisView1.setAdapter(new ImageAdapter(this));
// OnClick Item
lisView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
String sMemberID = MyArrList.get(position).get("MemberID").toString();
String sName = MyArrList.get(position).get("Name").toString();
String sTel = MyArrList.get(position).get("Tel").toString();
Intent newActivity = new Intent(MainActivity.this,DetailActivity.class);
newActivity.putExtra("MemberID", sMemberID);
startActivity(newActivity);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return MyArrList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColMemberID
TextView txtMemberID = (TextView) convertView.findViewById(R.id.ColMemberID);
txtMemberID.setPadding(10, 0, 0, 0);
txtMemberID.setText(MyArrList.get(position).get("MemberID") +".");
// R.id.ColName
TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
txtName.setPadding(5, 0, 0, 0);
txtName.setText(MyArrList.get(position).get("Name"));
// R.id.ColTel
TextView txtTel = (TextView) convertView.findViewById(R.id.ColTel);
txtTel.setPadding(5, 0, 0, 0);
txtTel.setText(MyArrList.get(position).get("Tel"));
return convertView;
}
}
public String getJSONUrl(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) { // Download 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();
}
}
I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html
In my code I used AQUery library to load image from web but it is showing null pointer exception at "aq.id(R.id.img);" in my code ...in class i created globle object of AQuery class and i define function inside inner class methode.....null pointer exception at "aq.id(R.id.img)" which is inside getview methode of cusomgrid class..
public class Customgrid extends Activity {
public int gotbread;
public int get, send;
AQuery aq;
String url1[] = { "https://www.dropbox.com/s/f308a9s5ycuc3mh/1.jpg",
"https://dl.dropbox.com/s/2s60g4e696566nt/2.jpg",
"https://dl.dropbox.com/s/59t6wo83ekzff0y/3.jpg",
"https://dl.dropbox.com/s/1b58qtj4ftm87yc/4.jpg",
"https://dl.dropbox.com/s/py7ogwstc0814zg/5.jpg",
"https://dl.dropbox.com/s/ocavtv1tkr6wtvv/6.jpg" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.customgview);
AQuery aq = new AQuery(Customgrid.this);
// Bundle gotbasket = getIntent().getExtras();
// gotbread = gotbasket.getInt("pos");
gotbread = getIntent().getExtras().getInt("position");
get = gotbread;
GridView grdview = (GridView) findViewById(R.id.gridView);
grdview.setAdapter(new Customgridadapter(this));
grdview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Bundle basket = new Bundle();
basket.putInt("position", send);
Intent i = new Intent(Customgrid.this,
FullScreenImageActivity.class);
i.putExtras(basket);
startActivity(i);
}
});
grdview.setVerticalSpacing(0);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
public class Customgridadapter extends BaseAdapter {
public Integer[] images1 = { R.drawable.s_1, R.drawable.s_2,
R.drawable.s_3 };
public Integer[] images2 = { R.drawable.s_5, R.drawable.s_6,
R.drawable.s_4 };
Context m1Context;
public Customgridadapter(Context context) {
super();
this.m1Context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return images1.length;
}
#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;
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
int pos = 0;
LayoutInflater inflater = ((Activity) m1Context)
.getLayoutInflater();
View customRow1 = inflater.inflate(R.layout.gview, null);
ImageView image = (ImageView) customRow1
.findViewById(R.id.imageforgrid);
aq.id(R.id.imageforgrid);
aq.image(url1[0],true,true);
Bitmap bm = DownloadImage(url1[0]);
switch (gotbread) {
case 0:
image.setImageBitmap(bm);
break;
case 1:
image.setImageBitmap(bm);
break;
}
image.setAdjustViewBounds(true);
image.setScaleX((float) 0.9);
image.setScaleY((float) 0.9);
switch (get) {
case 0:
send = get + position;
break;
case 1:
send = 10 * 1 + position;
break;
case 2:
send = 10 * 2 + position;
break;
case 3:
send = 10 * 3 + position;
break;
case 4:
send = 10 * 4 + position;
break;
}
// image.setOnClickListener(new OnImageClickListener(position));
return customRow1;
}
}
You have
AQuery aq = new AQuery(Customgrid.this); // declared and initialized in oncreate
in onCreate becomes local to onCreate.
Change to
aq = new AQuery(Customgrid.this);
The instance variable aq was never initialized giving NPE.
public class Customgrid extends Activity {
public int gotbread;
public int get, send;
AQuery aq; // not initialized
Also no network related operation on the ui thread.
I am creating an application which works offline. My app is working fine in online mode and getting json from url. How can I make it work offline? How do I insert json from a url into SQLite? I want to get all data from a url first, then insert it in SQLite and then use database.
This is my complete code:
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID",
Category_ID.get(position));
iMenuList.putExtra("Category_name",
Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.syddddds.pk/beta7/_webservices
/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add(Long.parseLong(object .getString("category_id")));
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image_path"));
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gridview.setAdapter(cla);
cla.notifyDataSetChanged();
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
androidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position),
true, true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}