Can't populate data from Asynctask? - java

In my App, I am parsing data from a Json file. It works Fine.Now I changed the code from my main thread to a Asynctask. I am new to Asynctask, so i can't find where i did the mistake. But in the logcat it show the Error is from the DoInBackground.
Thanks in Advance!
OLD CODE
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImageUrl(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Asynctask Code
public class News extends AsyncTask<JSONObject, Void, FeedListAdapter> {
JSONObject response;
protected FeedListAdapter doInBackground(JSONObject... params) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImageUrl(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(FeedListAdapter result) {
super.onPostExecute(result);
listAdapter.notifyDataSetChanged();
}
}
MY Class
public class FeedListActivity extends BaseActivity {
private static final String TAG = "FeedListActivity";
private ListView NewsView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
News mynews;
private String URL_FEED = "http://www.amsonsindia.net/ins/news.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_list);
setTitle(R.string.feed_list_demo);
mynews=new News();
mynews.execute();
NewsView = (ListView) findViewById(R.id.feed_list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
NewsView.setAdapter(listAdapter);
// making fresh volley request and getting json
GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
new Response.Listener<FeedResult>() {
#Override
public void onResponse(FeedResult response) {
feedItems = response.getFeedItems();
listAdapter.setData(feedItems);
listAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addRequest(gsonRequest, TAG);
getimg();
}
LOGCAT
Process: io.bxbxbai.feedlistviewdemo, PID: 2245
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at io.bxbxbai.androiddemos.activity.FeedListActivity$News.doInBackground(FeedListActivity.java:123)
at io.bxbxbai.androiddemos.activity.FeedListActivity$News.doInBackground(FeedListActivity.java:117)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

public class FeedListActivity extends BaseActivity {
private static final String TAG = "FeedListActivity";
private ListView NewsView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
News mynews;
private String URL_FEED = "http://www.amsonsindia.net/ins/news.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_list);
setTitle(R.string.feed_list_demo);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
// i just change feeditem position here
mynews=new News();
mynews.execute();
NewsView = (ListView) findViewById(R.id.feed_list);
NewsView.setAdapter(listAdapter);
// making fresh volley request and getting json
GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
new Response.Listener<FeedResult>() {
#Override
public void onResponse(FeedResult response) {
feedItems = response.getFeedItems();
listAdapter.setData(feedItems);
listAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addRequest(gsonRequest, TAG);
getimg();
}
----------
Replace your my class with above and put debug in doinbackgroud
and postexecute

In doInBackground method you cant update UI
change doinbackground code like this--
for (int i = 0; i < feedArray.length(); i++)
{
JSONObject feedObj = (JSONObject) feedArray.get(i);
publishProgress(feedObj.getInt("id"), feedObj.getString("status");
//so on..
}
and within aynctask add
protected void onProgressUpdate(final String... message) {
try {
FeedItem item = new FeedItem();
item.setId(message[0]);
item.setName(message[1);
and so on
feedItems.add(item);
} catch (Exception e) {
if (pd != null) {
pd.dismiss();
}
}
}

Related

How to fix java.lang.ClassCastException... cannot cast interface

In my main activity i have a fragment which displays weather information. I have an interface between the fragment and the main activity that sends data from fragment to activity. The problem is when trying to specifically enter the fragment activity the app crashes and this error is displayed.
Any help or any alternative ways doing it would be appreciated.
private void loadData() {
final List<WeatherForeCast> listWeatherForeCasts = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"https://www.metaweather.com/api/location/3534/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObject1 = jsonObject.getJSONObject("parent");
String cityCountry = jsonObject1.getString("title");
cityCountry = cityCountry + " ," + jsonObject.getString("title");
textViewCity.setText(Html.fromHtml(cityCountry ));
for (int x = 0; x < 6; x++) {
JSONObject weatherObject = array.getJSONObject(x);
WeatherForeCast weatherForeCast = new WeatherForeCast(
weatherObject.getInt("air_pressure"),
weatherObject.getInt("wind_speed"),
weatherObject.getInt("the_temp"),
weatherObject.getInt("humidity"),
weatherObject.getString("weather_state_name"),
weatherObject.getString("applicable_date"));
listWeatherForeCasts.add(weatherForeCast);
weatherState = listWeatherForeCasts.get(0).getWeatherState();
if(x == 0) {
sendData();
}
}
;
adapter = new Adapter(listWeatherForeCasts, getActivity());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
public void sendData()
{
Log.i("fault", weatherState);
getFirstWeatherInterface getFirstWeather = (getFirstWeatherInterface) getActivity();
getFirstWeather.getFirst(weatherState);
}
//Interface is implemented in the Activity
#Override
public WeatherForeCast getFirst(String string) {
Log.i("fault2", string);
return null
}
java.lang.ClassCastException: com.fan4.outdoorplus.WeatherFragments.WeatherActivity cannot be cast to com.fan4.outdoorplus.getFirstWeatherInterface
at com.fan4.outdoorplus.WeatherFragments.WeatherFragment.sendData(WeatherFragment.java:143)
at com.fan4.outdoorplus.WeatherFragments.WeatherFragment$1.onResponse(WeatherFragment.java:117)
at com.fan4.outdoorplus.WeatherFragments.WeatherFragment$1.onResponse(WeatherFragment.java:92)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Your problem is in this line. You are trying casting your activity to getFirstWeatherInterface
getFirstWeatherInterface getFirstWeather = (getFirstWeatherInterface) getActivity();

Parsing from MySQL database not displaying in Activity

I have these two activities in my Android application in which the first one is where the user will enter the asked information (to a edittext) and the other one is where it will send the data (I used putExtra to transfer the data from the 1st activity to the 2nd) to the MySQL database and will later on display results in ListView. The problem is, when the 2nd activity starts (considering that I have already entered something on the first activity) and after the progress dialog shows, there is nothing being displayed, or the results don't appear. But when I tried just starting the second activity (the edittext in the 1st activity is null) it shows the results. I'm not sure if what causes the problem, is on the application or in the PHP file I used in fetching the data?
Here are the codes:
MainActivity.java
//first activity
public class SearchFragment extends Fragment implements View.OnClickListener {
Button butt;
EditText destination;
String d;
public SearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
butt = (Button) view.findViewById(R.id.searchBUTTon);
butt.setOnClickListener(this);
destination = (EditText) view.findViewById(R.id.destinationTO);
return view;
}
#Override
public void onClick(View v) {
d = destination.getText().toString();
Intent a = new Intent(getActivity(), SearchResultsActivity.class);
a.putExtra("to", d);
startActivity(a);
}
}
SearchResultsAcivity.java
//second activity
public class SearchResultsActivity extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
private String JSON_STRING;
String destination;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
Intent a = getIntent();
destination = a.getStringExtra("to");
d = (TextView) findViewById(R.id.textView3);
d.setText(destination);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showBusList() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
//get strings
String id = jo.getString(config.TAG_ID);
String busName = jo.getString(config.TAG_BUSNAME);
String terminal = jo.getString(config.TAG_TERMINAL);
HashMap<String, String> busDetails = new HashMap<>();
busDetails.put(config.TAG_ID, id);
busDetails.put(config.TAG_BUSNAME, busName);
busDetails.put(config.TAG_TERMINAL, terminal);
list.add(busDetails);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
SearchResultsActivity.this, list, R.layout.result_list_item, new String[] {
config.TAG_ID, config.TAG_BUSNAME, config.TAG_TERMINAL}, new int[] {R.id.id, R.id.busName,
R.id.terminal});
listView.setAdapter(adapter);
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(SearchResultsActivity.this, "Message", "Fetching data... Please wait.", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showBusList();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(config.URL_SEARCH, destination);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
RequestHandler.java
//handles requests
public String sendGetRequestParam(String requestURL, String id){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s+"\n");
}
}catch(Exception e){
}
return sb.toString();
}
PHP file
<?php
$connection = mysqli_connect("mysql.hostinger.ph", "u679871488_bus", "Damnyoufudge20", "u679871488_bus") or die("Error " . mysqli_error($connection));
$des = $_GET['destination'];
$sql = "SELECT * from appDB WHERE route LIKE '%".$des."%'";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
$thisArray = array();
while($row = mysqli_fetch_assoc($result)) {
$thisArray[] = $row;
}
echo json_encode(array('busDetails' => $thisArray));
Error from logcat
03-06 16:10:25.525 31710-31710/com.thesis.iwander W/System.err: org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.thesis.iwander.SearchResultsActivity.showBusList(SearchResultsActivity.java:62)
at com.thesis.iwander.SearchResultsActivity.access$100(SearchResultsActivity.java:29)
at com.thesis.iwander.SearchResultsActivity$1GetJSON.onPostExecute(SearchResultsActivity.java:109)
at com.thesis.iwander.SearchResultsActivity$1GetJSON.onPostExecute(SearchResultsActivity.java:93)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
try array_push method in php in your php code
while($row = mysqli_fetch_assoc($result)) {
//$thisArray[] = $row;
array_push($thisArray, $row);
}
i think it'll work.
Try it once and check if get this data in android.
It is bad practice to append user input directly to sql query in php like you used '%".$des."%'. It causes SQL Injection Attacks.
Always prefer mysqli_prepare($sql) to avoid SQL Injection Attacks.
UPDATE 1
In SearchResultsActivity.java, try to replace
destination = a.getStringExtra("to");
this line with
destination = a.getExtras().getString("to");
Log.e("tag", " DESTINATION :: " + destination);
And check if you're getting the text from first activity.
UPDATE 2
Never ever forget to catch exceptions you're throwing.
You forgot to catch exception in sendGetRequestParam method. Catch it and print it. So you'll know if there is any error connecting to server.

Trying to parse json to list view on android but getting error

I am making a app which fetches json from my websites and parses that json to listview on android.
I get the json using http request then make 2 arrays websites t hold all websites names and links to hold links.I want the listview to show websites names and on clicking then open the website in the browser.
Can anyone please help me.Tried everything I could. Help me figure out the problem or tell me another way to do this thanks.
Trying To get the json and parse it into a listView Below is my code:
public class GetWebsiteList extends AsyncTask<String, String, String> {
// Creating JSON Parser object
ArrayList<HashMap<String, String>> productsList;
String websites[]=new String[10];
String links[]=new String[10];
// url to get all products list
private String url_all_products = "http://androidtest.cu.cc/getwebsites.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_WEBSITES = "websites";
private static final String TAG_SNO = "sno";
private static final String TAG_NAME = "name";
private static final String TAG_LINK = "link";
// products JSONArray
JSONArray products = null;
// Progress Dialog
private ProgressDialog pDialog;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mainpage.this);
pDialog.setMessage("Loading Website List.Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
//ArrayAdapter adapter = ArrayAdapter.
// Check your log cat for JSON reponse
Log.d("nitrek All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
String suc;
switch(success)
{
case 1:
suc="True";
break;
case 0:
suc="False";
break;
default:
suc="unkonwn";
break;
}
if (success == 1) {
// products found
// Getting Array of Products
Log.d(" nitrek success",suc);
products = json.getJSONArray(TAG_WEBSITES);
// looping through All Products
Log.d(" nitrek websites", products.toString());
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SNO);
String name = c.getString(TAG_NAME);
String link= c.getString(TAG_LINK);
Log.d("nitrek website",id+name+link);
// websites[i]=new String();
websites[i]=name;
links[i]=link;
Log.d("nitrek web",websites[i]+links[i]);
/* creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
try {
map.put(TAG_SNO, id);
map.put(TAG_NAME, name);
productsList.add(map);
}
catch (Exception e)
{
e.printStackTrace();
}
// adding HashList to ArrayList
*/
}
} else {
// no products found
// Launch Add New product Activity
Toast.makeText(mainpage.this,"no website found", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
*/
//ListAdapter adapter = new SimpleAdapter(mainpage.this, productsList, R.layout.listitem, new String[]{TAG_SNO, TAG_NAME},new int[]{R.id.sno, R.id.name});
// updating listview
try {
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(mainpage.this, R.layout.listitem, R.id.name, websites);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < websites.length; ++i) {
list.add(websites[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(mainpage.this, R.layout.listitem, list);
//ArrayAdapter<String> ad = new ArrayAdapter<String>(mainpage.this, R.layout.listitem, websites);
ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Intent intent = new Intent(this, homepage.class);
count = 0;
String url = links[position];
Toast.makeText(mainpage.this, "Opening: " + url, Toast.LENGTH_SHORT).show();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//notify_test(url);
startActivity(i);
}
});
} catch (Exception e) {
Log.d("error list nitrekerror", "below");
e.printStackTrace();
}
Toast.makeText(mainpage.this, result, Toast.LENGTH_LONG).show();
int i = 0;
while (i < websites.length && i < 3) {
Toast.makeText(mainpage.this, websites[i] + " " + links[i], Toast.LENGTH_LONG).show();
i++;
}
}
});
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
but I am getting this error and not able to figure out why?
Below is the logcat:
07-08 00:58:34.245 27826-27826/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: nitz.nitrek.myrtoguide, PID: 27826
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java)
at android.widget.AbsListView.obtainView(AbsListView.java)
at android.widget.ListView.measureHeightOfChildren(ListView.java)
at android.widget.ListView.onMeasure(ListView.java)
at android.view.View.measure(View.java)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.FrameLayout.onMeasure(FrameLayout.java)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java)
at android.widget.LinearLayout.measureVertical(LinearLayout.java)
at android.widget.LinearLayout.onMeasure(LinearLayout.java)
at android.view.View.measure(View.java)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:868)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.FrameLayout.onMeasure(FrameLayout.java)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java)
at android.widget.LinearLayout.measureVertical(LinearLayout.java)
at android.widget.LinearLayout.onMeasure(LinearLayout.java)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.FrameLayout.onMeasure(FrameLayout.java)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java)
at android.widget.LinearLayout.measureVertical(LinearLayout.java)
at android.widget.LinearLayout.onMeasure(LinearLayout.java)
at android.view.View.measure(View.java)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
at android.widget.FrameLayout.onMeasure(FrameLayout.java)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java)
at android.view.View.measure(View.java)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java)
at android.view.Choreographer.doCallbacks(Choreographer.java)
at android.view.Choreographer.doFrame(Choreographer.java)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
07-08 00:58:34.245 780-3917/? E/ActivityManager﹕ App crashed! Process: nitz.nitrek.myrtoguide
You had declared the websites array of size 10 but you were filling it with only 2-3 entries depending of number of websites you got as response so on passing the whole array to arrayadapter you were getting a null pointer exception.So you got the number of websites received in response and dynamically declared the array of that size only.
You have forgot to override getView off ArrayAdapter. And sync about viewHolder for more performance. You can read this https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView
You need to override this method to inflate your view else any view is create by your adapter and throw null Exception.
Example of override :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Object data = yourTabObj[position]
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_listView, parent, false);
}
// Lookup view for data population
TextView title = (TextView) convertView.findViewById(R.id.title);
title.setText(data.name);
// Return the completed view to render on screen
return convertView;
}
After you understand that think about viewHolder to increase performance.

Unable to populate ListView from ArrayList

ChooseCategory.java
public class ChooseCategory extends ListActivity {
private ListView lv;
//ArrayAdapter<FoodStores> arrayAdapter;
private ArrayList<FoodStores> storefoodList;
private String URL_STORES = "http://10.0.2.2/get_stores.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView)findViewById(R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
}
private class GetFoodStores extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if(json != null){
try{
JSONObject jsonObj = new JSONObject(json);
if(jsonObj != null){
JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
for(int i = 0; i < storeListFood.length(); i++){
JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
populateListView();
}
}
Here is the function of my populateListView
private void populateListView(){
List<String> labels = new ArrayList<String>();
for(int i = 0; i < storefoodList.size(); i++){
labels.add(storefoodList.get(i).getName());
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
Log.d("Labels:", labels.toString());
lv.setAdapter(listAdapter);
}
What I am trying to do here is to get the list of stores from PHP to Android via JSON and store them in ArrayList and then populate them into ListView. I have tried displaying labels, it is displaying the correct stuff.
The error from Emulator is that it just shows blank screen and then it crashes.
The error from logcat is
java.lang.NullPointerException
at call.rocket.user.callarocket.ChooseCategory.populateListView
Do like
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
setListAdapter(listAdapter);
as you directly extends ListActivity also remove
lv = (ListView)findViewById(R.id.list);
and make sure your ListView id is android:id="#android:id/list"
Go to Tutorial

Accessing External Database on an Android app

I am accessing an external database(000webhost) for fetching the email address in the app and printing them into a ListView. I am getting the correct response from the server which is printing in the logcat, but I am getting a null pointer exception.
This is what my logcat looks like:
05-11 16:00:39.891 24149-24914/info.androidhive.loginandregistration E/Entity Response:﹕ {"email":[{"email":"adeel#gmail.com"},{"email":"yamini#gmail.com"},{"email":"mona#gmail.com"}]}{"tag":"DisplayFriends","error":true,"error_msg":"Unknown 'tag' value. It should be either 'login' or 'register'"}
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
05-11 16:00:39.895 24149-24149/info.androidhive.loginandregistration D/AndroidRuntime﹕ Shutting down VM
05-11 16:00:39.898 24149-24149/info.androidhive.loginandregistration E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.loginandregistration, PID: 24149
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at info.androidhive.loginandregistration.FriendsList.setListAdapter(FriendsList.java:55)
at info.androidhive.loginandregistration.FriendsList$GetAllCustomerTask.onPostExecute(FriendsList.java:74)
at info.androidhive.loginandregistration.FriendsList$GetAllCustomerTask.onPostExecute(FriendsList.java:60)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Following are my java files:
ApiConnector.java
public class ApiConnector {
Global g=Global.getInstance();
String a=g.getLogInEmail();
String b="DisplayFriends";
public JSONArray GetAllCustomers()
{
// URL for getting all customers
// String url = "http://z.locationtest.comxa.com/index.php?tag=DisplayFriends&loggedInEmail="+a;
String url = "http://z.locationtest.comxa.com/index.php";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
HttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpPost httpPost = new HttpPost(url);
try
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", b));
params.add(new BasicNameValuePair("loggedInEmail", a));
httpPost.setEntity(new UrlEncodedFormEntity(params));
// HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray=null;
JSONObject jsonObject =null;
if (httpEntity != null)
{
try
{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response: ", entityResponse);
jsonObject = new JSONObject(entityResponse);
jsonArray = jsonObject.getJSONArray("email");
// jsonArray = new JSONArray(entityResponse);
/*for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
Log.d("TAG_LOCATIONS", jsonArray.toString(i));
}*/
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return jsonArray;
}
}
FriendList.java
public class FriendsList extends Activity {
private ListView listViewFriends;
private JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.listViewFriends=(ListView)this.findViewById(R.id.listViewFriends);
new GetAllCustomerTask().execute(new ApiConnector());
}
void setListAdapter(JSONArray jsonArray)
{
//this.jsonArray=jsonArray;
this.listViewFriends.setAdapter(new GetAllFriendsListViewAdapter(jsonArray,this));
}
private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
#Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllCustomers();
}
#Override
protected void onPostExecute(JSONArray jsonArray)
{
setListAdapter(jsonArray);
}
}
}
GetAllFriendsListViewAdapter.java
public class GetAllFriendsListViewAdapter extends BaseAdapter
{
private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater= null;
public GetAllFriendsListViewAdapter(JSONArray jsonArray, Activity a)
{
this.activity=a;
this.dataArray=jsonArray;
inflater= (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return this.dataArray.length();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ListCell cell;
if(convertView==null)
{
convertView=inflater.inflate(R.layout.item_layout,null);
cell=new ListCell();
cell.email=(TextView)convertView.findViewById(R.id.textViewFriends);
convertView.setTag(cell);
}
else
{
cell=(ListCell)convertView.getTag();
}
try
{
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.email.setText(" "+jsonObject.getString("email"));
}
catch(JSONException e)
{
e.printStackTrace();
}
return convertView;
}
private class ListCell
{
private TextView email;
}
}
I am new to Android. It would be great if someone help me find the error in my code.
A NullPointerException is thrown at runtime whenever your program
attempts to use a null as if it was a real reference.
So the error is not in getting the data from wherever you are hosting it. It is because you are trying to use a variable which is null.
You have done this private JSONArray jsonArray; but you need to do this too variable = new variable-type(); to allocate memory too. Please check the part above and do some googling. There is no error in getting the data, it is happening when you try to do something with it.
You are just declaring variables as below
private ListView listViewFriends;
private JSONArray jsonArray;
But this is not enough.
You need to define them in your code too.

Categories