Working with cursor objects in android - android

SplashActivity.java {Updated}
public class SplashActivity extends Activity {
/** Called when the activity is first created. */
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<HashMap<String, String>> arraylist;
private String Content;
DatabaseAdapter db;
TextView txtSplashTitle,txtSplashDesc;
DatabaseAdapter databaseHelper;
Cursor cursor;
//#InjectView(R.id.txtSplashDesc) TextView txtSplashDesc=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
//ButterKnife.inject(this);//using ButterKnife library for viewInjection
txtSplashDesc=(TextView) findViewById(R.id.txtSplashDesc);
String serverURL = "";
db = new DatabaseAdapter(this);
new LongOperation().execute(serverURL);
freeMemory();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Setting fonts for textviews
setCustomFontForTextViews();
}
private void setCustomFontForTextViews() {
Typeface typeFace = Typeface.createFromAsset(getAssets(), "royalacid.ttf");
txtSplashDesc.setTypeface(typeFace);
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(SplashActivity.this);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
Dialog.setMessage("Downloading source..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
// NOTE: Don't call UI Element here.
HttpGet httpget = new HttpGet("http://10.0.2.2:3009/findmybuffet/?storedproc=get_app_tables&flag=sudhakar");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
jsonobject = new JSONObject(Content);
jsonobject = jsonobject.getJSONObject("findmybuffet");
jsonarray = jsonobject.getJSONArray("buffets");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("buf_off_id", jsonobject.getString("buf_off_id"));
map.put("from_time", jsonobject.getString("from_time"));
map.put("to_time", jsonobject.getString("to_time"));
map.put("online_price", jsonobject.getString("online_price"));
map.put("reserved_price", jsonobject.getString("reserved_price"));
map.put("buf_image", jsonobject.getString("buf_image"));
map.put("res_name", jsonobject.getString("res_name"));
map.put("rating", jsonobject.getString("rating"));
map.put("latitude", jsonobject.getString("latitude"));
map.put("longitude", jsonobject.getString("longitude"));
map.put("buf_type_name", jsonobject.getString("buf_type_name"));
map.put("from_date", jsonobject.getString("from_date"));
map.put("to_date", jsonobject.getString("to_date"));
map.put("city_id", jsonobject.getString("city_id"));
map.put("city_name", jsonobject.getString("city_name"));
map.put("meal_type_id", jsonobject.getString("meal_type_id"));
map.put("meal_type_name", jsonobject.getString("meal_type_name"));
map.put("buf_desc", jsonobject.getString("buf_desc"));
map.put("distance", jsonobject.getString("distance"));
Log.d("----$$$----", map.toString());
//Calling database
db.addContact(map);
try {
Cursor cursor = (Cursor) databaseHelper.getAllContacts();
cursor.moveToFirst();
if(cursor.moveToFirst()){
do{
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
Log.d("---#*#*#*#*#*#----", refDestLatitude+"");
}while(cursor.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ThrownException", e.toString());
e.printStackTrace();
}
//cursor.close();
}
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
} catch (IOException|JSONException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// Close progress dialog
Dialog.dismiss();
Intent intent=new Intent(SplashActivity.this,MainActivitySherlock.class);
startActivity(intent);
}
}
private void freeMemory() {
jsonobject=null;
jsonarray=null;
arraylist=null;
Content=null;
}
}
When i debugged the app i found as below
I am having problem in the line ::
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
Cursor is able to get the value
cursor.getColumnIndex(cursor.getColumnName(7))
But exception popps up when
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
is evaluated
Note:: This line was working when i was handling in adapter ..... but its not working here. do i need to cast a reference or something ?

try like this :
if(c.moveToFirst()){
do{
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
}while(c.moveToNext())
}

cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
You get an error because there is no column 7.
I have to ask why all the drama when you could just get the data from the column?
if (getColumnCount() > 11) { // 4+7 = 11 fail
cursor.getString(7);
}

Related

Android application crashes if JSON is empty

I am developing an Application of JSON object Which Returns data into ListView.
if json have data then show data in listview..if dont have date then application is crashes.my application is crashes when json is empty.how to resolve this problem..thanx in advancce
here is android code..
public class EmployeePaymentHistory extends Fragment {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
ListView CategoryListView;
ProgressBar progressBar;
List<String> IdList = new ArrayList<>();
private String TAG = EmployeePaymentHistory.class.getSimpleName();
// Http Url For Filter Student Data from Id Sent from previous activity.
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
String TempItem;
ProgressDialog progressDialog2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_employee_payment, container, false);
CategoryListView = (ListView)view.findViewById(R.id.listview1);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getActivity().getIntent().getExtras().getString("ListViewValue1");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
// Add Click listener on Delete button.
return view;
}
// Method to Delete Student Record
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new EmployeePaymentHistory.GetHttpResponse(getActivity()).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("CustomerID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, api.EmployeePayment);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
List<Customer> CategoryList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Customer category;
CategoryList = new ArrayList<Customer>();
for(int i=0; i<jsonArray.length(); i++)
{
category = new Customer();
jsonObject = jsonArray.getJSONObject(i);
category.CustomerName = jsonObject.getString("date").toString();
category.Customertotal = jsonObject.getString("account").toString();
category.CustomerPaid = jsonObject.getString("total").toString();
category.CustomerUnPaid = jsonObject.getString("status").toString();
CategoryList.add(category);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "abcc", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
CategoryListView.setVisibility(View.VISIBLE);
CustomerListAdapterClass adapter = new CustomerListAdapterClass(CategoryList, context);
CategoryListView.setAdapter(adapter);
}
}
}
here is php Api code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$CustomerID= $_POST['CustomerID'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "sELECT b.payerid,a.account as account,b.date as date,b.status as status,b.type as type,sum(b.amount) as total FROM crm_employees a left JOIN sys_transactions b ON a.id = b.payerid where payerid= '$CustomerID' group by b.date ORDER BY a.id desc" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
You need to give the response output same as you are parsing in android side. If you are trying to find a Json object of key name which is not in response then it will crash.
In this scenario you need to handle manually, the values you think it will be null or empty then handle using normal if statements.
Suppose jsonObject.getString("date") object is not fount then using if statements you can handle.
if(jsonObject.getString("date") != null){
//code here
}

Json String to Image

So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest

How to add item into listview dynamically

I want to add item into listview using async task, so in doinbackgroud it will process and get the data one by one and then display it on listview one by one .
But for my app doinbackground process all the data and then it will display into listview.
public class NewGetContacts extends AsyncTask<String[], Void, Void> {
private static final String TAG_TX = "txid";
private static final String TAG_FEE = "fees";
MyCustomAdapter mAdapter=new MyCustomAdapter();
ListView listViewHandle1 = (ListView) findViewById(R.id.listView2);
#Override
protected Void doInBackground(String[]... params) {
// TODO Auto-generated method stub
int len = params[0].length;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
// String jsonStr;
mAdapter.addSeparatorItem("Transaction ...");
for(int i=0;i<len ;i++){
String turl = "https://coin/api/tx/"+params[0][i];
try {
String jsonStr1 = sh.makeServiceCall(turl, ServiceHandler.GET);
JSONObject jsonObj2 = new JSONObject(jsonStr1);
txtid = jsonObj2.getString(TAG_TX);
mAdapter.addItem("Transaction ID : "+txtid);
publishProgress();
}catch(Exception e){
Log.d("Exception In TXID -- >",e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Void... r) {
super.onProgressUpdate(r);
Log.d("Txid 14546465 ","--->");
mAdapter.notifyDataSetChanged();
listViewHandle1.requestLayout();
super.onProgressUpdate(r);
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listViewHandle1.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
Call this in oncreate on your activity/fragment
Class TestActivity extends Activty {
MyCustomAdapter mAdapter ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAdapter=new MyCustomAdapter();
ListView listViewHandle1 = (ListView) findViewById(R.id.listView2);
listViewHandle1.setAdapter(mAdapter);
(new NewGetContacts()).execute();
}
}
Then do following in your AsyncTask class
protected Void doInBackground(String[]... params) { //Same as yours
// TODO Auto-generated method stub
int len = params[0].length;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
// String jsonStr;
mAdapter.addSeparatorItem("Transaction ...");
for(int i=0;i<len ;i++){
String turl = "https://coin/api/tx/"+params[0][i];
try {
String jsonStr1 = sh.makeServiceCall(turl, ServiceHandler.GET);
JSONObject jsonObj2 = new JSONObject(jsonStr1);
txtid = jsonObj2.getString(TAG_TX);
mAdapter.addItem("Transaction ID : "+txtid);
publishProgress();
}catch(Exception e){
Log.d("Exception In TXID -- >",e.getMessage());
}
}
return null;
}
protected void onProgressUpdate(Void... r) {
super.onProgressUpdate(r);
mAdapter.notifyDataSetChanged();
Log.d("Txid 14546465 ","--->");
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Removed set adapter from here
mAdapter.notifyDataSetChanged();
}

Empty listView in listFragment

I have a list fragment. When I run the app, I see an empty listView.
I don't know what the problem is. Maybe I should use a library?
public class MyEmployeFragment extends ListFragment {
private static final String ATTRIBUTE_ID = "p_id";
private static final String ATTRIBUTE_NAME = "p_name";
private static final String ATTRIBUTE_LAST_NAME = "p_last_name";
ArrayList<spr_item> ret_data;
MyTask task;
SimpleAdapter sAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
task = new MyTask();
task.execute();
return inflater.inflate(R.layout.my_employe, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ret_data = new ArrayList<spr_item>();
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
ret_data.size());
Map<String, Object> m;
for (int i = 0; i < ret_data.size(); i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_ID, ret_data.get(i).getId());
m.put(ATTRIBUTE_NAME, ret_data.get(i).getName());
m.put(ATTRIBUTE_LAST_NAME, ret_data.get(i).getLastName());
data.add(m);
}
// массив имен атрибутов, из которых будут читаться данные
String[] from = {ATTRIBUTE_ID, ATTRIBUTE_NAME, ATTRIBUTE_LAST_NAME};
// массив ID View-компонентов, в которые будут вставлять данные
int[] to = {R.id.tw_employe_id, R.id.tw_employe_name, R.id.tw_employe_last_name};
// создаем адаптер
sAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_item_employee,
from, to);
// определяем список и присваиваем ему адаптер
ListView lvSimple = (ListView) getView().findViewById(android.R.id.list);
lvSimple.setAdapter(sAdapter);
}
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
String s = "5ACACEC6-752B-4EFF-AA50-EEBE58A52113";
// String user_guid = myPrefs.getString("guid", "");
HttpActivity _http = new HttpActivity("192.168.10.11", "80");
_http.set_addr_protocol("/WebSite/P/spr/spr.aspx/");
_http.add_param("query", "spr_employee_get");
// _http.add_param("p_guid", user_guid.toString().trim());
_http.add_param("p_guid", s);
_http.send();
List<spr_item> tempList = _http.getArrayParamValue();
for(int i = 0; i < tempList.size(); i++)
ret_data.add(tempList.get(i));
//employer_name = _http.getArrayParamValue("p_name");
//employer_id = _http.getArrayParamValue("p_id");
//employer_last_name = _http.getArrayParamValue("p_last_name");
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
sAdapter.notifyDataSetChanged();
}
}
}
With the above code apart from the Empty list you may have the null pointer exception too if the task is too quick to load. Here onCreate is called first onCreateView next and onActvityCreated next. So it is better to initialise adapter in onCreate set the adapter to listView in onCreateView and set listView listeners in onActvityCreated using getListView() method.
Apart from this if you are using local database to retrieve data you need to use cursorADapter to fetch the data
The adapter's data references (ArrayList, array, etc.), tend to get lost pretty easily. In that case the notfiyDataSetChanged() method will not work. If you are adamant on using this method I suggest you check the references to the adapter's source again. If that is not the case this is the approach I've used in my project. A small warning in advance, the formatting and the closing of brackets is poorly executed, but the approach is still clear enough.
public class MyFragment extends ListFragment {
// For populating the list view.
SomeAdapter adapter;
public MyFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] parameters = {"url for request"};
new GetRequestTask().execute(parameters);
}
// The async task to make the HTTP GET requests.
class GetRequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.e("GetRequestTask", "Client protocol exception.");
e.printStackTrace();
} catch (IOException e) {
Log.e("GetRequestTask", "IO exception.");
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Update UI with the new response.
new UpdateUITask().execute(result);
}
}
}
// The async task to update the UI.
class UpdateUITask extends AsyncTask<String, String, ArrayList<Something>>{
#Override
protected ArrayList<Something> doInBackground(String... input) {
ArrayList<Something> someArray = new ArrayList<Something>();
try{
// Do some JSON magic to parse the data.
}
catch(JSONException je){
Log.e("UpdateUITask", "JSON parsing error occured.");
je.printStackTrace();
}
return someArray;
}
#Override
protected void onPostExecute(ArrayList<Something> result) {
super.onPostExecute(result);
Log.i("UpdateUITask", "Updating UI.");
adapter = new SomeAdapter(getActivity(), R.layout.some_list_item, restOfTheParameters);
setListAdapter(adapter);
}
}
}
}

How to execute Asynctask simultaneously

I have two asynctask in one class and i am having trouble in executing them at the same time.
Here is my scenario, my the user clicks the view january calendar button it will show up the events for the month of calendar and the comments for it. The events and comments are stored in mysql database so i have to fetch different url. I used asyctask to fetch the url. Whenever i call the other asynctask it cannot be resolved. help me out!
Here is my code:
package sscr.stag;
#SuppressLint("ShowToast")
public class Calendar extends ListActivity {
// All xml labels
TextView txtEvent;
// Progress Dialog
private ProgressDialog pDialog;
JSONArray user;
JSONObject hay;
private static final String CALENDAR_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryCalendar.php";
private static final String COMMENT_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryReadComment.php";
private static final String TAG_USER = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_TIME = "time";
private static final String TAG_ARRAY = "posts";
private JSONArray mCalendar = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendaradmin);
txtEvent = (TextView) findViewById(R.id.event);
new LoadCalendar().execute();
new LoadCommentCal().execute(); // error here, says cannot be resolved in this type
}
private class LoadCalendar extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Calendar.. ");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String json = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CALENDAR_URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(COMMENT_URL);
try {
mCalendar = json.getJSONArray(TAG_ARRAY);
for (int i = 0; i < mCalendar.length(); i++) {
JSONObject c = mCalendar.getJSONObject(i);
String username = c.getString(TAG_USER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, username);
mCommentList.add(0, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(Calendar.this, mCommentList,
R.layout.calendar_comment, new String[] { TAG_MESSAGE,
TAG_USER, TAG_TIME }, new int[] { R.id.message,
R.id.username, R.id.time });
setListAdapter(adapter);
ListView lv = getListView();
lv.scrollTo(0, 0);
}
public class LoadCommentCal extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... args) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
}
Your second asynctask public class LoadCommentCal extends AsyncTask is inside the first asynctask!
You need to move it out of the first asynctask.
private class LoadCalendar extends AsyncTask<String, String, String> {
...
}
... other functions
private class LoadCommentCal extends AsyncTask<Void, Void, String> {
...
}
You are declaring lots of things inside the first AsyncTask I strongly reccomend to close your AsyncTask after the onPostExecute
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
and then removing one } at the end of the java file (and also reindent if you wish)

Categories

Resources