Cannot cast from FragmentActivity to ListFragment - android

This error shows up when i do this:
This is in the MainActivity:
ListView lv = ((ListFragment) getActivity()).getListView();
but if I don't cast it to that the app crashes and I get
01-02 22:35:00.285: E/AndroidRuntime(17289): FATAL EXCEPTION: main
01-02 22:35:00.285: E/AndroidRuntime(17289): Process: com.titanhash.teamdoge, PID: 17289
01-02 22:35:00.285: E/AndroidRuntime(17289): java.lang.IllegalStateException: Content view not yet created
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
01-02 22:35:00.285: E/AndroidRuntime(17289): at com.titanhash.teamdoge.WorkersFragment.onCreate(WorkersFragment.java:70)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.view.Choreographer.doFrame(Choreographer.java:543)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.os.Handler.handleCallback(Handler.java:733)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.os.Looper.loop(Looper.java:136)
01-02 22:35:00.285: E/AndroidRuntime(17289): at android.app.ActivityThread.main(ActivityThread.java:5081)
01-02 22:35:00.285: E/AndroidRuntime(17289): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 22:35:00.285: E/AndroidRuntime(17289): at java.lang.reflect.Method.invoke(Method.java:515)
01-02 22:35:00.285: E/AndroidRuntime(17289): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
01-02 22:35:00.285: E/AndroidRuntime(17289): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-02 22:35:00.285: E/AndroidRuntime(17289): at dalvik.system.NativeStart.main(Native Method)
I will post the rest of the code If you guys need it. Ooh also I am calling the list fragment from the MainActivity with:
This is in the MainActivity
case 3:
return WorkersFragment.newInstance("Workers");
And the ListFragment instance:
This is in the ListFragment
public static WorkersFragment newInstance(String text) {
WorkersFragment pageFragment = new WorkersFragment();
return pageFragment;
}
Thanks for the help ahead of time!
BIG - EDIT:
Here is the activity code:
package com.titanhash.teamdoge;
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class SuchActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_such);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.such, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return TeamdogeFragment.newInstance("Teamdoge");
case 1:
return PoolFragment.newInstance("Pool");
case 2:
return UserFragment.newInstance("User");
case 3:
return WorkersFragment.newInstance("Workers");
}
return TeamdogeFragment.newInstance("Teamdoge");
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
}
Here is the ListFragment code:
package com.titanhash.teamdoge;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.support.v4.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class WorkersFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "";
// JSON Node names
private static final String TAG_DASHDATA = "getdashboarddata";
private static final String TAG_DATA = "data";
private static final String TAG_PERSONAL = "personal";
private static final String TAG_WORKERS = "workers";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_HASHRATE = "hashrate";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray workers = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
public static WorkersFragment newInstance(String text) {
WorkersFragment pageFragment = new WorkersFragment();
return pageFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.worker_layout, container, false);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contactList = 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 name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),SingleContactActivity.class);
in.putExtra(TAG_ID, name);
in.putExtra(TAG_USERNAME, cost);
in.putExtra(TAG_HASHRATE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
//pDialog = new ProgressDialog(SuchActivity.this);
//pDialog.setMessage("Please wait...");
//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);
JSONObject jsonObject;
if (jsonStr != null) {
try {
//JSONObject jsonObj2 = new JSONObject(jsonStr);
// Get the root JSONObject
jsonObject = new JSONObject(jsonStr);
// Get the JSON object named query
//JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getpoolstatus");
JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getdashboarddata");
// Get the JSON object named results inside of the query object
//JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
// Get the JSON object named quote inside of the results object
JSONObject personalJSONObject = dataJSONObject.getJSONObject("personal");
// Getting JSON Array node
workers = personalJSONObject.getJSONArray(TAG_WORKERS);
// looping through All Contacts
for (int i = 0; i < workers.length(); i++) {
JSONObject c = workers.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_USERNAME);
String email = c.getString(TAG_HASHRATE);
//String address = workers.getString(TAG_ADDRESS);
//String gender = workers.getString(TAG_GENDER);
// Phone node is JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
//String mobile = phone.getString(TAG_PHONE_MOBILE);
//String home = phone.getString(TAG_PHONE_HOME);
//String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, "ID: " + id);
contact.put(TAG_USERNAME, name);
contact.put(TAG_HASHRATE, email + " kH/s");
//contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} 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(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_ID, TAG_USERNAME,
TAG_HASHRATE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
ANOTHER EDIT:
package com.titanhash.teamdoge;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class WorkersFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://teamdoge.com/index.php?page=api&action=getdashboarddata&api_key=5a0a4793431873828540ae6ddad556075b169180d5b16023a41daec8530b890f&id=2317";
// JSON Node names
private static final String TAG_DASHDATA = "getdashboarddata";
private static final String TAG_DATA = "data";
private static final String TAG_PERSONAL = "personal";
private static final String TAG_WORKERS = "workers";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_HASHRATE = "hashrate";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray workers = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
public static WorkersFragment newInstance(String text) {
WorkersFragment pageFragment = new WorkersFragment();
return pageFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.worker_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contactList = 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 name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),SingleContactActivity.class);
in.putExtra(TAG_ID, name);
in.putExtra(TAG_USERNAME, cost);
in.putExtra(TAG_HASHRATE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
//pDialog = new ProgressDialog(SuchActivity.this);
//pDialog.setMessage("Please wait...");
//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);
JSONObject jsonObject;
if (jsonStr != null) {
try {
//JSONObject jsonObj2 = new JSONObject(jsonStr);
// Get the root JSONObject
jsonObject = new JSONObject(jsonStr);
// Get the JSON object named query
//JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getpoolstatus");
JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getdashboarddata");
// Get the JSON object named results inside of the query object
//JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
// Get the JSON object named quote inside of the results object
JSONObject personalJSONObject = dataJSONObject.getJSONObject("personal");
// Getting JSON Array node
workers = personalJSONObject.getJSONArray(TAG_WORKERS);
// looping through All Contacts
for (int i = 0; i < workers.length(); i++) {
JSONObject c = workers.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_USERNAME);
String email = c.getString(TAG_HASHRATE);
//String address = workers.getString(TAG_ADDRESS);
//String gender = workers.getString(TAG_GENDER);
// Phone node is JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
//String mobile = phone.getString(TAG_PHONE_MOBILE);
//String home = phone.getString(TAG_PHONE_HOME);
//String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, "ID: " + id);
contact.put(TAG_USERNAME, name);
contact.put(TAG_HASHRATE, email + " kH/s");
//contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} 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(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_ID, TAG_USERNAME,
TAG_HASHRATE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}

You can't cast the Activity to a Fragment; they are completely different, and you are already inside the Fragment instance.
You can't call the getList() method from onCreate(), because the Views aren't initialized at this point; you should move that logic to onViewCreated() instead.

java.lang.IllegalStateException:Content view not yet created
Move the code in onCreate to onActivityCreated. Override onActivityCreated.
Edit:
public class WorkersFragment extends Fragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://teamdoge.com/index.php?page=api&action=getdashboarddata&api_key=5a0a4793431873828540ae6ddad556075b169180d5b16023a41daec8530b890f&id=2317";
// JSON Node names
private static final String TAG_DASHDATA = "getdashboarddata";
private static final String TAG_DATA = "data";
private static final String TAG_PERSONAL = "personal";
private static final String TAG_WORKERS = "workers";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_HASHRATE = "hashrate";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
JSONArray workers = null;
ListView lv;
ArrayList<HashMap<String, String>> contactList;
public static WorkersFragment newInstance(String text) {
WorkersFragment pageFragment = new WorkersFragment();
return pageFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.worker_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
lv = (ListView) getView().findViewById(R.id.listView1);
contactList = new ArrayList<HashMap<String, String>>();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.textView1))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.textView2))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.textView3))
.getText().toString();
// Starting single contact activity
// Intent in = new Intent(getActivity().getApplicationContext(),SingleContactActivity.class);
// in.putExtra(TAG_ID, name);
// in.putExtra(TAG_USERNAME, cost);
// in.putExtra(TAG_HASHRATE, description);
// startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(url);
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
if (_response!= null) {
//JSONObject jsonObj2 = new JSONObject(jsonStr);
// Get the root JSONObject
JSONObject jsonObject = new JSONObject(_response);
// Get the JSON object named query
//JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getpoolstatus");
JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getdashboarddata");
// Get the JSON object named results inside of the query object
//JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
// Get the JSON object named quote inside of the results object
JSONObject personalJSONObject = dataJSONObject.getJSONObject("personal");
workers = personalJSONObject.getJSONArray(TAG_WORKERS);
for (int i = 0; i < workers.length(); i++) {
JSONObject c = workers.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_USERNAME);
String email = c.getString(TAG_HASHRATE);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, "ID: " + id);
contact.put(TAG_USERNAME, name);
contact.put(TAG_HASHRATE, email + " kH/s");
contactList.add(contact);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_ID, TAG_USERNAME,
TAG_HASHRATE }, new int[] { R.id.textView1,
R.id.textView2, R.id.textView3});
lv.setAdapter(adapter);
}
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="33dp"
android:layout_marginTop="40dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_marginRight="26dp"
android:text="TextView" />
</RelativeLayout>
wokers_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
Snap

You can't do this: ((ListFragment) getActivity()).getListView();
The ListView you're looking for is in the ListFragment you are hosting in that Activity.
Time to go back to school…
Please review the documentation for a ListFragment, an Activity and how to communicate between Fragments (and Activities).
The answer is there and it will help you understand the problem.

Related

Exception java.util.List.size() raised for unknown reason

Following exception is thrown:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:100)
at android.widget.ListView.setAdapter(ListView.java:491)
at android.app.ListActivity.setListAdapter(ListActivity.java:265)
at com.example.example.feed.ActivityFeedActivity$GetStudents.onPostExecute(ActivityFeedActivity.java:93)
at com.example.example.feed.ActivityFeedActivity$GetStudents.onPostExecute(ActivityFeedActivity.java:47)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Code:
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ActivityFeedActivity extends ListActivity {
// URL to get contacts JSON
private static String url = "https://raw.githubusercontent.com/mobilesiri/JSON-Parsing-in-Android/master/index.html";
// JSON Node names
private static final String TAG_STUDENTINFO = "studentsinfo";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityfeed);
// Calling async task to get json
new GetStudents().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetStudents extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ActivityFeedActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webreq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
studentList = ParseJSON(jsonStr);
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(
ActivityFeedActivity.this, studentList,
R.layout.feed_item, new String[]{TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE}, new int[]{R.id.name,
R.id.email, R.id.mobile});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray students = jsonObj.getJSONArray(TAG_STUDENTINFO);
// looping through All Students
for (int i = 0; i < students.length(); i++) {
JSONObject c = students.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
// tmp hashmap for single student
HashMap<String, String> student = new HashMap<String, String>();
// adding each child node to HashMap key => value
student.put(TAG_ID, id);
student.put(TAG_NAME, name);
student.put(TAG_EMAIL, email);
student.put(TAG_PHONE_MOBILE, mobile);
// adding student to students list
studentList.add(student);
}
return studentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
return null;
}
}
}
If I understand this correctly, there should be data in studentList parsed from the url when OnPostExecute() method executes, so what am I missing that causes the exception to be thrown anyway?
The problem could be with your JSON parsing implementation since you return null if JSONException is raised or with the actual request because you also return null in the case when JSON wasn't successfully fetched. Is there another exception in LogCat before crash?

Why do I have java.lang.NullPointerException at multiple libraries in Android in trying to Parse JSON

I am trying to parse a JSON format in my Android Application. I am fairly new in developing android applications so I am referring to a lot of tutorials. I followed the steps in this tutorial : http://mobilesiri.com/json-parsing-in-android-using-android-studio/
Here is my MainActivity.java class :
package com.example.carlajoyce.parsejson;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private static String url = "http://tech.ccare.jrhernani.com/tech/workorders";
private static final String TAG_WORKORDERINFO = "workorders";
private static final String TAG_ID = "id";
private static final String TAG_SUBJECT = "subject";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_INITIATED = "initiated";
private static final String TAG_FINISHED = "finished";
private static final String TAG_CREATEDAT = "created_at";
private static final String TAG_UPDATEDAT = "updated_at";
private static final String TAG_TICKETID = "ticket_id";
private static final String TAG_CREATEDBYID = "createdBy_id";
private static final String TAG_TECHNICIANID = "technician_id";
private static final String TAG_WORKORDERREFID = "workorderref_id";
private static final String TAG_WORKORDERSTATUSID = "workorderstatus_id";
private static final String TAG_DEPARTMENTID = "department_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetWorkOrders().execute();
}
/**
*Async task class to get JSON by making HTTP call
*/
private class GetWorkOrders extends AsyncTask<Void, Void, Void> {
/*HashMap for ListView*/
ArrayList<HashMap<String, String>> workOrderList;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
/*Creating service handler class instance*/
WebRequest webreq = new WebRequest();
/* Making a request to url and getting response*/
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GETRequest);
Log.d("Response: ", "> " + jsonStr);
workOrderList = ParseJSON(jsonStr);
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, workOrderList,
R.layout.list_item, new String[]{TAG_SUBJECT, TAG_DESCRIPTION}, new int[]{R.id.subject, R.id.description});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> workOrderList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray workOrders = jsonObj.getJSONArray(TAG_WORKORDERINFO);
// looping through All WorkOrders
for (int i = 0; i < workOrders.length(); i++) {
JSONObject c = workOrders.getJSONObject(i);
String id = c.getString(TAG_ID);
String subject = c.getString(TAG_SUBJECT);
String description = c.getString(TAG_DESCRIPTION);
String initiated = c.getString(TAG_INITIATED);
String finished = c.getString(TAG_FINISHED);
String created_at = c.getString(TAG_CREATEDAT);
String updated_at = c.getString(TAG_UPDATEDAT);
String ticket_id = c.getString(TAG_TICKETID);
String createdBy_id = c.getString(TAG_CREATEDBYID);
String technician_id = c.getString(TAG_TECHNICIANID);
String workorderref_id = c.getString(TAG_WORKORDERREFID);
String workorderstatus_id = c.getString(TAG_WORKORDERSTATUSID);
String department_id = c.getString(TAG_DEPARTMENTID);
// tmp hashmap for single student
HashMap<String, String> workOrder = new HashMap<String, String>();
// adding each child node to HashMap key => value
workOrder.put(TAG_ID,id);
workOrder.put(TAG_SUBJECT, subject);
workOrder.put(TAG_DESCRIPTION, description);
workOrder.put(TAG_INITIATED, initiated);
workOrder.put(TAG_FINISHED, finished);
workOrder.put(TAG_CREATEDAT, created_at);
workOrder.put(TAG_UPDATEDAT, updated_at);
workOrder.put(TAG_TICKETID, ticket_id);
workOrder.put(TAG_CREATEDBYID, createdBy_id);
workOrder.put(TAG_TECHNICIANID, technician_id);
workOrder.put(TAG_WORKORDERREFID, workorderref_id);
workOrder.put(TAG_WORKORDERSTATUSID, workorderstatus_id);
workOrder.put(TAG_DEPARTMENTID, department_id);
// adding student to students list
workOrderList.add(workOrder);
}
return workOrderList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url.");
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have a basic understanding of how the code works and I fixed some problems that occurred without having to ask here but I met a problem on I don't know where to begin. I am hoping you can tell me the reason for these errors:
02-16 17:51:31.294 6378-6378/com.example.carlajoyce.parsejson E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.carlajoyce.parsejson, PID: 6378
java.lang.NullPointerException
at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)
at android.widget.ListView.setAdapter(ListView.java:480)
at android.app.ListActivity.setListAdapter(ListActivity.java:265)
at com.example.carlajoyce.parsejson.MainActivity$GetWorkOrders.onPostExecute(MainActivity.java:93)
at com.example.carlajoyce.parsejson.MainActivity$GetWorkOrders.onPostExecute(MainActivity.java:49)
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:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:801)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
at dalvik.system.NativeStart.main(Native Method)
NOTE: I also downloaded the code the tutorial provided and it works just fine.
Thanks in advance.
I think you should first initialize adapter and view with empty list, so move this:
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, workOrderList,
R.layout.list_item, new String[]{TAG_SUBJECT, TAG_DESCRIPTION}, new int[]{R.id.subject, R.id.description});
setListAdapter(adapter);
to onCreate() in MainActivity, and when job is finished - in onPostExecute() just notify adapter that data set changed.
adapter.notifyDataSetChanged();
Please let me know if it works for you.
It happens if the workOrderList is null.
You have to initialize this list before calling the constructor of your adapter.
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, workOrderList,
R.layout.list_item, new String[]{TAG_SUBJECT, TAG_DESCRIPTION}, new int[]{R.id.subject, R.id.description});
It happens because your ParseJSON (called in the doInBackground method) can return null

NullPointerException on onCreateView when using Fragment and listview

I have converted Many Activities to Fragment, all are working fine except one. It gives Null Pointer Exception on setOnItemClickListener. I have checked many similar questions, but unable to figure out the problem. If anyone can provide correct code with explanation for problem.
Problem is at this line as given by debugger:
lv.setOnItemClickListener(new OnItemClickListener() {
Following is Code:
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.net.URLConnection;
import android.support.v4.app.Fragment;
public class listtojson extends Fragment {
private ProgressDialog pDialog;
public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listnews.php";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
private static final String TAG_PHONE_URL = "url";
private static final String TAG_FILETYPE = "filetype";
private static final String TAG_FILETYPETXT = "filetypetxt";
private static final String TAG_DETAILS = "details";
private static final String TAG_FILEPATH = "filepath";
private static final String TAG_LOCATION = "location";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_USERNAME = "username";
private static final String TAG_HIGHALERT= "highalert";
public int ssid ;
// contacts JSONArray
JSONArray contacts = null;
public TextView view1;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
RelativeLayout llLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentActivity faActivity = (FragmentActivity) super.getActivity();
llLayout = (RelativeLayout) inflater.inflate(R.layout.listnewsjson, container, false);
contactList = new ArrayList<HashMap<String, String>>();
lv = (ListView) llLayout.findViewById(R.id.list); //getListView();
// ListView lv = getActivity().getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String size = ((TextView) view.findViewById(R.id.size))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String details = ((TextView) view.findViewById(R.id.details))
.getText().toString();
String location = ((TextView) view.findViewById(R.id.location))
.getText().toString();
String datetime = ((TextView) view.findViewById(R.id.datetime))
.getText().toString();
String filetype = ((TextView) view.findViewById(R.id.filetypetxt))
.getText().toString();
String username = ((TextView) view.findViewById(R.id.username))
.getText().toString();
Intent in = new Intent(getActivity().getApplicationContext(), jsondetailActivity.class);
// passing sqlite row id
//= in.putExtra(TAG_ID, sqlite_id);
in.putExtra(TAG_ID, String.valueOf(id));
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_DETAILS, details);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_DATETIME, datetime);
in.putExtra(TAG_FILETYPE, filetype);
in.putExtra(TAG_PHONE_URL, description);
in.putExtra(TAG_SIZE, size);
in.putExtra(TAG_USERNAME, username);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
return llLayout;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading People News");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
try {
// Making a request to url and getting response
// String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
URL requestUrl = new URL(url);
Log.e("Debug", " Sapp 1 : " + requestUrl.toString());
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
//Reader rd=new Readable(in);
int cp;
try {
while((cp=in.read())!=-1){
sb.append((char)cp);
}}
catch(Exception e){
}
String jsonStr=sb.toString();
Log.e("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String url = c.getString(TAG_PHONE_URL);
String details = c.getString(TAG_DETAILS);
String location = c.getString(TAG_LOCATION);
String datetime = c.getString(TAG_DATETIME);
String filetype = c.getString(TAG_FILETYPE);
String username = c.getString(TAG_USERNAME);
String highalert = c.getString(TAG_HIGHALERT);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_SIZE, size);
contact.put(TAG_PHONE_URL, url);
contact.put(TAG_DETAILS, details);
contact.put(TAG_LOCATION, location);
contact.put(TAG_DATETIME, datetime);
contact.put(TAG_FILETYPE, filetype);
contact.put(TAG_FILETYPETXT, filetype);
contact.put(TAG_USERNAME, username);
contact.put(TAG_HIGHALERT, highalert);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}catch(Exception ec){
}
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(
getActivity(), contactList,
R.layout.list_selector, new String[] { TAG_NAME, TAG_SIZE,
TAG_PHONE_URL,TAG_FILETYPE, TAG_FILETYPETXT,TAG_DETAILS,TAG_LOCATION,TAG_DATETIME, TAG_USERNAME, TAG_HIGHALERT}, new int[] { R.id.name,
R.id.size, R.id.url, R.id.filetype,R.id.filetypetxt, R.id.details, R.id.location, R.id.datetime, R.id.username, R.id.highalert });
Log.e("Debug", " Sapp 10"+TAG_NAME);
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view.getId() == R.id.name) {
((TextView) view).setText((String) data);
return true;
} else if (view.getId() == R.id.size) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.url) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.details) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.location) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.datetime) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.filetypetxt) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.username) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10,20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert=(String.valueOf((String) data));
if(halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
return true;
}
else { return true; }
} else if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res =getResources();
String tnew=(String.valueOf((String) data));
String tst=tnew;
int sidd=0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if(tst.equals("c")) { ssid = R.drawable.ca; }
else if(tst.equals("d")) { ssid = R.drawable.da; }
else if(tst.equals("e")) { ssid = R.drawable.ea; }
// Log.e("Debug", " Sapp 8 :"+ssid+":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
};
((SimpleAdapter) adapter).setViewBinder(viewBinder);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
}
public static String getFileSize(long size) {
if (size <= 0)
return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
And here is the Logcat:
10-14 00:46:53.900 18286-18286/com.sjssoft.sawdhan E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sjssoft.sawdhan, PID: 18286
java.lang.NullPointerException
at com.sjssoft.sawdhan.listtojson.onCreateView(listtojson.java:87)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1072)
at android.support.v4.view.ViewPager.populate(ViewPager.java:918)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:248)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:543)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5052)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
And here is XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
/>
</RelativeLayout>
#android:id/list uses the ID "list" from the Android package, so you need to reference it as findViewById(android.R.id.list) in your Java code.
Try this:
View fragment = inflater.inflate(R.layout.your_fragment_layout, container, false);
lv = (ListView) fragment.findViewById(android.R.id.list);
Your ArrayList needs to be like this:
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>
Instead of :
llLayout = (RelativeLayout) inflater.inflate(R.layout.listnewsjson, container, false);
insert this:
View v = inflater.inflate(R.layout.listnewsjson, container, false);
lv = (ListView) v.findViewById(android.R.id.list);
...
new GetContacts().execute();
return v;
Your AsyncTask needs to be like this:
AsyncTask<Void, Void, ArrayList<HashMap<String, String>>
Your doInBackground needs to be like this:
ArrayList<HashMap<String, String>> doInBackground(Void... params)
Your onPostExecute needs to be like this:
onPostExecute(ArrayList<HashMap<String, String>> result)
set adapter:
lv.setAdapter(new SomeAdapter(getActivity().getApplicationContext(), result));
...

Show listview picture and details using picasso

i am try to display and image in listview in android and it is not showing i have beening trying it for a while now. i have a database and i have put in url or images thier name and id .. and i want the listview to show the images and thier detail.
but it is giving me errors ... can anyone help me..
it is telling me category not found..
package com.example.cann;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class CategoryActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// ALL JSON node names
private static final String TAG_POSTS = "posts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "category";
public static final String TAG_CATEGORIES_COUNT = "categories_count";
public static final String TAG_CATEGORIES_LOGO = "categories_logo";
private static final String URL_CATEGORY = "http://10.0.2.2/music/selectm.php";
// albums JSONArray
JSONArray categories = null;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// private ListView lv;
private BaseAdapter mAdapter;
ArrayList<HashMap<String, String>> categoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
// Hashmap for ListView
categoryList = new ArrayList<HashMap<String, String>>();
Log.d("onCreate: ", "Yep");
new LoadComments().execute();
}
public void yess(){
// get listview
ListView lv = getListView();
lv.setDivider(null);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
Toast.makeText(CategoryActivity.this, "Item selected: " + position,
Toast.LENGTH_LONG).show();
// Uncomment this to start a new Activity for a chosen item
/* Intent i = new Intent(getApplicationContext(),
ItemListActivity.class);
String category_id = ((TextView) view
.findViewById(R.id.category_id)).getText()
.toString();
i.putExtra("category_id", category_id);
startActivity(i);*/
}
});
}
public void upd(){
categoryList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_CATEGORY);
try {
categories = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < categories.length(); i++) {
JSONObject c =categories.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_CATEGORIES_COUNT);
String category_logo = c.getString(TAG_CATEGORIES_LOGO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_CATEGORIES_COUNT, songs_count);
map.put(TAG_CATEGORIES_LOGO, category_logo);
categoryList.add(map);
// adding HashList to ArrayList
}
mAdapter = new CategoryListAdapter(CategoryActivity.this,
categoryList);
getListView().setAdapter(mAdapter);
// dismiss the dialog after getting all albums
pDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
upd();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
pDialog.dismiss();
yess();
}
});
}
}
}
package com.example.cann;
import java.util.ArrayList;
import java.util.HashMap;
import com.squareup.picasso.Picasso;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CategoryListAdapter extends BaseAdapter {
private Context mContext;
LayoutInflater inflater;
private final ArrayList<HashMap<String, String>> urls;
HashMap<String, String> resultp = new HashMap<String, String>();
public static final String CATEGORY_LOGO_URL = "http://10.0.2.2/demi.jpg";
public CategoryListAdapter(Context context,
ArrayList<HashMap<String, String>> items) {
mContext = context;
urls = items;
}
#Override
public int getCount() {
return urls.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView category_name;
ImageView category_logo;
TextView item_count;
TextView item_id;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_list_category, parent,
false);
resultp = urls.get(position);
category_name = (TextView) view.findViewById(R.id.category_name);
category_logo = (ImageView) view.findViewById(R.id.img_category_logo);
item_count = (TextView) view.findViewById(R.id.songs_count);
item_id = (TextView) view.findViewById(R.id.category_id);
category_name.setText(resultp.get(CategoryActivity.TAG_NAME));
item_count.setText(resultp.get(CategoryActivity.TAG_CATEGORIES_COUNT));
item_id.setText(resultp.get(CategoryActivity.TAG_ID));
// Picasso image loader library starts here
Picasso.with(mContext)
.load(CATEGORY_LOGO_URL
+ resultp.get(CategoryActivity.TAG_CATEGORIES_LOGO)) // Photo URL
.placeholder(R.drawable.placeholder) // This image will be displayed while photo URL is loading
.error(R.drawable.error) // if error shows up during downloading
.fit().centerCrop() // settings
.into(category_logo); // we put it into our layout component (imageview)
return view;
}
}
and i have tested my php script and it is displaying image
require("config.inc.php");
$query = "Select * FROM music";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["TAG_ID"] = $row["id"];
$post[" TAG_NAME"] = $row["Artist"];
$post["TAG_CATEGORIES_COUNT"] = $row["Song"];
$post["TAG_CATEGORIES_LOGO"] = $row["Artpics"];
array_push($response["posts"], $post);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
my Logcat
09-13 07:38:59.020: W/System.err(1315): org.json.JSONException: No value for id
09-13 07:38:59.220: W/System.err(1315): at org.json.JSONObject.get(JSONObject.java:355)
09-13 07:38:59.220: W/System.err(1315): at org.json.JSONObject.getString(JSONObject.java:515)
09-13 07:38:59.260: W/System.err(1315): at com.example.cann.CategoryActivity.upd(CategoryActivity.java:103)
09-13 07:38:59.260: W/System.err(1315): at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:148)
09-13 07:38:59.270: W/System.err(1315): at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:1)
09-13 07:38:59.270: W/System.err(1315): at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-13 07:38:59.270: W/System.err(1315): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-13 07:38:59.270: W/System.err(1315): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-13 07:38:59.270: W/System.err(1315): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-13 07:38:59.270: W/System.err(1315): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-13 07:38:59.270: W/System.err(1315): at java.lang.Thread.run(Thread.java:841)
Try to replace this peace of code :
String id = c.getString("TAG_ID");
String name = c.getString("TAG_NAME");
String songs_count = c.getString("TAG_CATEGORIES_COUNT");
String category_logo = c.getString("TAG_CATEGORIES_LOGO");
Also remove space from this :
$post[" TAG_NAME"] replace to $post["TAG_NAME"]
Note : your using wrong key to get data from json.
public class CategoryActivity extends ListActivity {
private static final String TAG_POSTS = "posts";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "category";
public static final String TAG_CATEGORIES_COUNT = "categories_count";
public static final String TAG_CATEGORIES_LOGO = "categories_logo";
private static final String URL_CATEGORY = "http://10.0.2.2/music/selectm.php";
private BaseAdapter mAdapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
lv = getListView();
lv.setDivider(null);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) {
Toast.makeText(CategoryActivity.this, "Item selected: " + position,
Toast.LENGTH_LONG).show();
// Uncomment this to start a new Activity for a chosen item
/* Intent i = new Intent(getApplicationContext(),
ItemListActivity.class);
String category_id = ((TextView) view
.findViewById(R.id.category_id)).getText()
.toString();
i.putExtra("category_id", category_id);
startActivity(i);*/
}
});
new LoadComments().execute();
}
class LoadComments extends AsyncTask<Void, Void, ArrayList<HashMap<String,String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_CATEGORY);
try {
JSONArray categories = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < categories.length(); i++) {
String id = categories.getJSONObject(i).getString("TAG_ID");
String name = categories.getJSONObject(i).getString("TAG_NAME");
String songs_count = categories.getJSONObject(i).getString("TAG_CATEGORIES_COUNT");
String category_logo = categories.getJSONObject(i).getString("TAG_CATEGORIES_LOGO");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_CATEGORIES_COUNT, songs_count);
map.put(TAG_CATEGORIES_LOGO, category_logo);
categoryList.add(map);
}
}catch (Throwable e){
e.printStackTrace();
}
return categoryList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(pDialog.isShowing()){
pDialog.dismiss();
}
mAdapter = new CategoryListAdapter(CategoryActivity.this,result);
lv.setAdapter(mAdapter);
}
}
}

List view activity showing objects only the first time it is opened

In my Android app I have a list view activity showing MySQL objects downloaded from a web server via JSON.
I have detected following issue: the first time the activity is shown, the JSON objects are shown fine, but if the user goes back to the previous activity and then opens the list view activity again, any object is shown on the list and no error is thrown.
I need your help to solve this issue. Here is the activity code:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ofertas_list extends ListActivity {
private ProgressDialog pDialog;
// JSON node keys
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// URL to get contacts JSON
private static String url = "http://xxxxxxxx/android_ofertaslist.php?id=";
// JSON Node names
private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
private static final String TAG_IDEMPRESA = "idEmpresa";
private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
private static final String TAG_STRIMAGEN = "strImagen";
private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
private static final String TAG_EMAILEMPRESA = "emailEmpresa";
private static final String TAG_TEXTOOFERTA = "textoOferta";
private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
// getting intent data
Intent in = getIntent();
// JSON node keys
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_ID);
// URL to get contacts JSON
this.url = url+email;
this.setTitle(name);
contactList = 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
//cambiar por los nuevos campos
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
//cambiar por los nuevos campos
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ofertas_list.this);
pDialog.setMessage("Cargando datos...");
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
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
String strImagen = c.getString(TAG_STRIMAGEN);
String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
String textoOferta = c.getString(TAG_TEXTOOFERTA);
String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
String idEmpresa = c.getString(TAG_IDEMPRESA);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_IDEMPRESA, idEmpresa);
contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
contact.put(TAG_STRIMAGEN,strImagen);
contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
contact.put(TAG_EMAILEMPRESA,emailEmpresa);
contact.put(TAG_TEXTOOFERTA,textoOferta);
contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);
// adding contact to contact list
contactList.add(contact);
}
} 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(
ofertas_list.this, contactList,
R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
UPDATED CODE:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ofertas_list extends ListActivity {
private ProgressDialog pDialog;
// JSON node keys
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idCategoria";
private static final String TAG_CATEGORIAS = "Categorias";
// URL to get contacts JSON
private static String url = "http://xxxxxxx/android_ofertaslist.php?id=";
// URL to get contacts JSON
// private static String url = "http://mujercanariasigloxxi.appgestion.eu/app_php_files/android_ofertaslist.php";
// JSON Node names
private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
private static final String TAG_IDEMPRESA = "idEmpresa";
private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
private static final String TAG_STRIMAGEN = "strImagen";
private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
private static final String TAG_EMAILEMPRESA = "emailEmpresa";
private static final String TAG_TEXTOOFERTA = "textoOferta";
private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";
#Override
public void onResume(){
super.onResume();
new GetContacts().execute();
}
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
// getting intent data
Intent in = getIntent();
// JSON node keys
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_ID);
// URL to get contacts JSON
this.url = url+email;
this.setTitle(name);
contactList = 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
//cambiar por los nuevos campos
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
//Starting single contact activity
//cambiar por los nuevos campos
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, cost);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ofertas_list.this);
pDialog.setMessage("Cargando datos...");
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
contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
String strImagen = c.getString(TAG_STRIMAGEN);
String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
String textoOferta = c.getString(TAG_TEXTOOFERTA);
String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
String idEmpresa = c.getString(TAG_IDEMPRESA);
// Phone node is JSON Object
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_IDEMPRESA, idEmpresa);
contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
contact.put(TAG_STRIMAGEN,strImagen);
contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
contact.put(TAG_EMAILEMPRESA,emailEmpresa);
contact.put(TAG_TEXTOOFERTA,textoOferta);
contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);
// adding contact to contact list
contactList.add(contact);
}
} 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(
ofertas_list.this, contactList,
R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
R.id.email });
setListAdapter(adapter);
}
}
}
You should probably perform the "new GetContacts().execute();" call in onResume(). See the Android documentation to get more familiar with the Android Activity lifecyle.
onCreate() is only called when the Activity is created. In your testing, the Activity is probably usually still alive, so onCreate() will not always be called when re-entering the Activity.
Put your new GetContacts().execute() in onResume() method.
onCreate() is called when you start Activity for the first time. If you leave activity, without killing it, and come back, your app goes thru onStart() ->onResume()`
Put onResume right before onCreate and remove new GetContacts().execute(); from onCreate().
...
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onResume(){
super.onResume();
new GetContacts().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
...

Categories

Resources