Empty listView in listFragment - android

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

Related

Android, after reading data from MySQL, listview populates after screen display is off

I am trying to fetch data from MySQL database and display it in listview. The data is successfully retrieved but the listview is not populated until the screen display is off. Progress dialog also doesn't appear until the listview is populated. Any suggestions?
public class BestLinksActivity extends AppCompatActivity {
public ListView myListView;
public MyListViewAdapter mAdapter;
public List<HotelInfo> dataSource;
private String cityName;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_best_links);
dataSource = new ArrayList<>();
mProgressDialog = new ProgressDialog(BestLinksActivity.this);
mProgressDialog.setMessage("Loading data...");
Bundle extras = getIntent().getExtras();
if (extras != null) {
cityName = extras.getString("City");
}
DataBaseReader dbReader = new DataBaseReader();
if (!(cityName.equals(null))) {
dbReader.execute(cityName);
} else {
Toast.makeText(getApplicationContext(), "City name not specified", Toast.LENGTH_SHORT).show();
}
//Create adapter
mAdapter = new MyListViewAdapter(getApplicationContext(), dataSource);
//Configure the listview
myListView = (ListView) findViewById(R.id.main_list_view);
myListView.setAdapter(mAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item value
HotelInfo currentItem = dataSource.get(position);
//Open url of the currentItem in web browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentItem.getLinkUrl())));
}
});
}
public String getTitle(String url) {
String[] subStrings = url.split("/");
String urlTitle = "";
for (int i = 0; i < subStrings.length; i++) {
if (subStrings[i].equals("t"))
urlTitle = (subStrings[i + 1]);
}
urlTitle = urlTitle.replace("-", " ");
urlTitle=((urlTitle.charAt(0)+"").toUpperCase()).concat(urlTitle.substring(1));
return urlTitle;
}
public class DataBaseReader extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.build();
Log.d("CheckParam", params[0]);
RequestBody postBody = new FormBody.Builder()
.add("cityName", params[0])
.build();
Request myRequest = new Request.Builder()
.url("http://172.18.0.32/extractData.php")
.post(postBody)
.build();
String serverResponse = null;
try {
Response response = okHttpClient.newCall(myRequest).execute();
serverResponse = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject myJsonObj = new JSONObject(serverResponse);
JSONArray myJsonArray = myJsonObj.getJSONArray("server_response");
for (int index = 0; index < myJsonArray.length(); index++) {
JSONObject linkObject = myJsonArray.getJSONObject(index); //Otherwise, you will get last element
HotelInfo myHotelInfo = new HotelInfo();
myHotelInfo.setLinkUrl(linkObject.getString("Link"));
myHotelInfo.setLinkTitle(getTitle(myHotelInfo.getLinkUrl()));
dataSource.add(myHotelInfo);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Log.d("MyKeyser", serverResponse);
return serverResponse;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("MyKey", s);
if (mProgressDialog!=null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
}
Add the following line to your onPostExecute:
mAdapter.notifyDataSetChanged();
You need to notify your adapter that the data had changed.
See the docs.
Regarding the ProgressBar, you need to put it under some Layout in your activity_best_links layout.
The best way would be to not create it programatically, but add it to your xml layout file, see example here, and then play with its visibility via mProgress.setVisibility();

Get an Arraylist from an inner class

I am seeking help so that I may get an ArrayList<String> in an alternate class. As you can see in the following code I have inner and outer classes. Both work as expected and I am both able to insert values and fetch details from my online database using php scripts (I have commented out these details for code clarity as it was taking up a lot of space).
public class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 15000;
public static final String SERVER_ADDRESS = "// my url domain";
public ArrayList<String> list1 = new ArrayList<>();
public ServerRequests(Context context)
{
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please wait..");
}
public void storeDataInBackground(MultiChallenge multiChallenge)
{
progressDialog.show();
new StoreDataAsyncTask(multiChallenge).execute();
}
public class StoreDataAsyncTask extends AsyncTask<Void , Void , Void>
{
MultiChallenge multiChallenge;
public StoreDataAsyncTask(MultiChallenge multiChallenge)
{
this.multiChallenge = multiChallenge;
}
#Override
protected Void doInBackground(Void... voids) {
// where I insert values...
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
Log.d("ServerRequests", "Post execute");
}
}
public ArrayList<String> fetchDataInBackground() {
progressDialog.show();
new FetchDataAsyncTask().execute();
return list1;
}
public class FetchDataAsyncTask extends AsyncTask<Void, Void, ArrayList<String>>
{
public FetchDataAsyncTask()
{
}
String text = "";
#Override
protected ArrayList<String> doInBackground(Void... params) {
InputStream is1;
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(// my url domain+ "// php script");
try {
HttpResponse httpResponse = client.execute(post);
is1 = httpResponse.getEntity().getContent();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(is1, "iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
JSONArray data = new JSONArray(text);
for (int i = 0; i < data.length(); i++) {
Log.d("GetNames", data.getString(i));
JSONObject jsonData = data.getJSONObject(i);
list1.add( // I successfully add details to list1 here, I have commented it out for code clarity);
}
for (int iterate = 0; iterate < list1.size(); iterate++) {
Log.d("list1", list1.get(iterate));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// catch (JSONException e) {e.printStackTrace();}
return list1;
}
#Override
protected void onPostExecute(ArrayList<String> myList) {
progressDialog.dismiss();
super.onPostExecute(myList);
}
}
}
Now that I successfully add to the list1 (I can tell values are added to it because of the for loop with the int iterate), I now need to send it to another class whereby I will put items in a listview. This is my code in the class in which I want to display the details of the ArrayList I get from ServerRequests:
ServerRequests serverRequests = new ServerRequests(DisplayInfo.this);
ArrayList<String> myList = new ArrayList<>();
myList = serverRequests.fetchDataInBackground();
for (int iterate = 0; iterate < myList.size(); iterate++) {
Log.d("Display", myList.get(iterate));
However the above for loop is never called, indicating that myList is never given the details that list1 manages to get in the doInBackground method of class FetchDataAsync.
Please note I did spend a number of hours attempting a variety of my own ideas and answers derived from SO before asking this question. Thank you all in advance of your help.
In the onPostExecute method call a function in the calling class
#Override
protected void onPostExecute(ArrayList<String> myList) {
progressDialog.dismiss();
super.onPostExecute(myList);
MainActivity.sendStrings(myList);
}
In the calling function implement a method:
public static void sendStrings(ArrayList<String> strings)
{
//Add for loop here
}
Alternatively you can also use interfaces. Call the interface in onPostExecute and implement the interface in the calling class

Passing data from onPostExecute() to adapter

Can't pass data from onPostExecute() to adapter for my AutoComleteTextView. Logcat shows me:
An exception occurred during performFiltering()! java.lang.NullPointerException: collection == null.
public class UzActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
List<String> responseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uz);
final String url = "http://booking.uz.gov.ua/purchase/station/%D0%9A%D0%B8%D0%B5/";
new FetchStationTask().execute(url);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, responseList);
textView.setAdapter(adapter);
}
private class FetchStationTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
try {
return new UzFetcher().getUrlString(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result){
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
StationResponse st = objectMapper.readValue(result, StationResponse.class);
responseList = new ArrayList<>();
for (int i = 0; i<st.mStations.size(); i++){
responseList.add(st.mStations.get(i).getTitle());
}
Log.i(DEBUG_TAG, responseList.get(0));
} catch (IOException e) {
e.printStackTrace();
}
Log.i(DEBUG_TAG, result);
}
}
java.lang.NullPointerException: collection == null.
ArrayList should be initialized first.
Just add,
responseList = new ArrayList<String>();
after setContentView();

android AsyncTask and UI thread interaction

I'm using the AsyncTask to open a URL, access the server, fetch the content and display them in a list view in the main activity. The content extracted consists of a title of the newspaper and a URL to the website, which will be displayed on a WebView in a second activity, if a "read" button is clicked. I coded out the program straight away and it works, but when I looked back at it, I found something that seems unreasonable, so mainly I want to make clear how the code works. Here is the code for the main activity:
package com.example.newsapp;
public class MainActivity extends Activity {
static final private String LOG_TAG = "main";
private ArrayList<Content> aList;
private class Content{
Content() {};
public String title;
public String url;
}
private class MyAdapter extends ArrayAdapter<Content>{
int resource;
public MyAdapter(Context _context, int _resource, List<Content> titles) {
super(_context, _resource, titles);
resource = _resource;
// this.context = _context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout newView;
final Content content = getItem(position);
// Inflate a new view if necessary.
if (convertView == null) {
newView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(inflater);
vi.inflate(resource, newView, true);
} else {
newView = (LinearLayout) convertView;
}
// Fills in the view.
TextView tv = (TextView) newView.findViewById(R.id.listText);
ImageButton b = (ImageButton) newView.findViewById(R.id.listButton);
b.setBackgroundResource(0);
tv.setText(content.title);
Typeface type = Typeface.createFromAsset(getAssets(),"LiberationSerif-BoldItalic.ttf");
tv.setTypeface(type);
// Sets a listener for the button, and a tag for the button as well.
b.setTag(Integer.toString(position));
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Reacts to a button press.
Intent intent = new Intent(MainActivity.this, WebPage.class);
Bundle bundle = new Bundle();
bundle.putString("URL", content.url);
intent.putExtras(bundle);
startActivity(intent);
}
});
return newView;
}
}
class MyAsyncTask extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
Content content;
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Downloading the news...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(String... params) {
String url_select = params[0];
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return result;
} // protected Void doInBackground(String... params)
protected void onPostExecute(String result) {
//parse JSON data
try {
super.onPostExecute(result);
Log.i(LOG_TAG, result);
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("sites");
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
content = new Content();
if (jObject.has("title") && jObject.has("url")){
content.title = jObject.getString("title");
content.url = jObject.getString("url");
aList.add(content);
aa.notifyDataSetChanged();
}
} // End Loop
progressDialog.dismiss();
} catch (JSONException e) {
// progressDialog.dismiss();
Log.e("JSONException", "Error: " + e.toString());
}
} // protected void onPostExecute(String result)
}
private MyAdapter aa;
private MyAsyncTask loadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadTask = new MyAsyncTask();
loadTask.execute("http://luca-ucsc.appspot.com/jsonnews/default/news_sources.json");
aList = new ArrayList<Content>();
aa = new MyAdapter(this, R.layout.list_element, aList);
ListView myListView = (ListView) findViewById(R.id.listView1);
myListView.setAdapter(aa);
aa.notifyDataSetChanged();
}
public void refresh(View v){
if (loadTask.getStatus() == AsyncTask.Status.FINISHED){
aList.clear();
aa.notifyDataSetChanged();
new MyAsyncTask().execute("http://luca-ucsc.appspot.com/jsonnews/default/news_sources.json");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
So you can see that only after loadTask.execute() in onCreate(), do I create the object for alist and aa, but I'm already using them in onPostExecute() in the AsyncTaks class, so I'm not very clear what happens here, because onPostExecute() and the UI are on the same thread, so the code in onPostExecute() should be executed first.
I thought I should put
aList = new ArrayList<Content>();
aa = new MyAdapter(this, R.layout.list_element, aList);
into onPostExecute(), which is more logical to me, but the app crashes this way. Also I think deleting aa.notifyDataSetChanged(); in onPostExecute() shouldn't be a problem because it's also in the onCreate() method, but this actually causes the list view to be blank, without any content. Actually, putting any of the codes after loadTask.execute() into the if block of the onPostExecute() method causes some problem, or crashes the app. That would be great if somebody can give some insight or hint. Thanks for reading.
onPostExecute is called on the UI thread after the background task completes its work. You cannot guarantee the timing of this call in relation to other calls on the UI thread.
Since you are already implementing getView yourself, I recommend you extend BaseAdapter instead of ArrayAdapter and implement the other few required methods. It's not hard and you can use whatever data structure you want to back the adapter. Assuming you use a List<Content> to back the adapter, you can write a method to swap the list in place like so:
public void swapList(List<Content> newList) {
this.list = newList;
notifyDataSetChanged();
}
In your AsyncTask, you have complete control of the Params, Progress, and Result parameterized types. They don't all have to be String. You can do this instead:
private class myAsyncTask extends AsyncTask<String, Void, List<Content>> {
/* ... */
}
The String for Params is the URL (same as you do now). Void for Progress because you don't publish progress anyway. List<Content> for Result because that's the thing you actually want to end up with after doing your task.
You should do ALL of your work in doInBackground. There is no reason to deserialize a String into a JSONArray and mess around with that in onPostExecute, particularly since that is happening on the main thread. Rewrite doInBackground to return a List<Content>, and all you need in onPostExecute is this:
public void onPostExecute(List<Content> result) {
adapter.swapList(result);
}
Now you can create the adapter once (in onCreate()) and just swap the list whenever it's appropriate.

Working with cursor objects in 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);
}

Categories

Resources