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));
...
Related
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);
}
}
}
I am working on learning JsonParsing. In that I have some category_list array. I parse data from that array and bind it to a listView in android. From that list I also again have to make an API call to that Web-service and check that sub-category are there or not ? If there is no sub category then it will be product list. i have tried as below but i have unable to parse from productList json
How to decide or give me any solution logic for it. My code is as below:
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.epe.yehki.backend.ServiceHandler;
import com.epe.yehki.uc.Header;
import com.example.yehki.R;
import android.R.string;
import android.app.Activity;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SubCategoryActivity extends ListActivity {
// SUB CATEGORIES...
private static final String TAG_CAT_LlIS = "categories_list";
private static final String TAG_CAT_ID = "category_id";
private static final String TAG_CAT_NAME = "category_name";
int flag;
public Header header;
public TextView title;
// PRODUCTS....
private static final String TAG_PRODUCT_ID = "product_id";
private static final String TAG_PRODUCT_LlST = "product_list";
private static final String TAG_PRODUCT_NAME = "product_name";
private static final String TAG_PRODUCT_IMG = "image";
private static final String TAG_PRODUCT_DESCRIPTION = "detail_description";
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
String name;
JSONObject jsonObj;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://yehki.epagestore.in/app_api/categories.php";
private static String mainurl = "http://yehki.epagestore.in/";
public String suburl = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
this.header = (Header) findViewById(R.id.headersubcat);
title = (TextView) findViewById(R.id.title);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
try {
catid = in.getStringExtra(TAG_CAT_ID);
name = in.getStringExtra(TAG_CAT_NAME);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("::::::::::::::MY CATEGORY ID::::::::::::::IN SUB "
+ catid);
subcategoryList = new ArrayList<HashMap<String, String>>();
suburl = "http://yehki.epagestore.in/app_api/categories.php?"
+ TAG_CAT_ID + "=" + catid;
System.out.println("::::::::::::::::MY SUBCATEGORY URL::::::::::::"
+ suburl);
title.setText(name);
// Displaying all values on the screen
ListView lv = getListView();
new GetSubCategories().execute();
// 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 catname = ((TextView) view.findViewById(R.id.name))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SubCategoryTwoActivity.class);
in.putExtra(TAG_CAT_NAME, catname);
in.putExtra(TAG_CAT_ID, catid);
startActivity(in);
}
});
}
private class GetSubCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SubCategoryActivity.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();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::"
+ suburl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(suburl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(TAG_CAT_LlIS)) {
subcategories = jsonObj.getJSONArray(TAG_CAT_LlIS);
if (subcategories != null
&& subcategories.length() != 0) {
// looping through All Contacts
flag = 0;
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ subcategories.length());
for (int i = 0; i < subcategories.length(); i++) {
JSONObject c = subcategories.getJSONObject(i);
id = c.getString(TAG_CAT_ID);
String name = c.getString(TAG_CAT_NAME);
// tmp hashmap for single category
HashMap<String, String> subcategory = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
subcategory.put(TAG_CAT_ID, id);
subcategory.put(TAG_CAT_NAME, name);
// adding contact to contact list
subcategoryList.add(subcategory);
}
}
} else {
flag = 1;
products = jsonObj.getJSONArray(TAG_PRODUCT_LlST);
System.out
.println("==========SIZE OF MY ARRAY PRODUCT LIST==================="
+ products.length());
System.out
.println(":::::::::::::::::::Product array:::::::::::::::"
+ products);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject p = products.getJSONObject(i);
String proId = p.getString(TAG_PRODUCT_ID);
String proName = p.getString(TAG_PRODUCT_NAME);
String productImg = p.getString(TAG_PRODUCT_IMG);
String productDesc = p
.getString(TAG_PRODUCT_DESCRIPTION);
System.out
.println("::::::::::::::::MY PRODUCT DETAILS::::::::::::::"
+ TAG_PRODUCT_ID
+ " PRODUCT NAME "
+ TAG_PRODUCT_NAME
+ " PRODUCT_DESCRIPTION "
+ TAG_PRODUCT_DESCRIPTION
+ " PRODUCT IMAGE "
+ TAG_PRODUCT_IMG);
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
// product.put(TAG_PRODUCT_ID, proId);
product.put(TAG_PRODUCT_NAME, proName);
product.put(TAG_PRODUCT_DESCRIPTION, productDesc);
/*
* product.put(TAG_PRODUCT_IMG, productImg);
*/
productList.add(product);
}
}
} 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
*
* */
if (flag == 0) {
ListAdapter adapter = new SimpleAdapter(
SubCategoryActivity.this, subcategoryList,
R.layout.list_item, new String[] { TAG_CAT_NAME },
new int[] { R.id.name });
setListAdapter(adapter);
} else {
ListAdapter adapter = new SimpleAdapter(
SubCategoryActivity.this, subcategoryList,
R.layout.activity_single_produt, new String[] {
TAG_PRODUCT_NAME, TAG_PRODUCT_DESCRIPTION,
TAG_PRODUCT_IMG }, new int[] {
R.id.product_label, R.id.product_desc,
R.id.iv_product_img });
setListAdapter(adapter);
}
}
}
}
try this:
if(jsonObj.has("name_of_the_field")){
//yes
}
or
JSONArray mJSONArray = jsonObj.optJSONArray("name of array");
the method optJSONArray("nameofarray") will return a null JSONArray if it could not find the JSONArray with provided name.
hmm there is one method to check if the key exists or not in json.
like if you have json array and you want to check if there is subcategory than
call method on that array object.
The JSONObject has method to check if the key exists in the JSON or not.
Quoting from the docs.
public boolean has (String name)
//Returns true if this object has a mapping for name. The mapping may be NULL.
You can find the official doc here
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);
...
I have a listview now i need to pass the listview data to a another activity how do i do it ?
MainActivity
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import java.util.List;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String url = "http://216.185.116.35/LOGISTIC/WebServices/json/getDeliveriItems_bak.ashx?id=485";
private static final String TAG_OS = "android";
private static final String TAG_VER = "BagNumber";
private static final String TAG_NAME = "COD";
private static final String TAG_API = "OrderNo";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java
package learn2crack.listview.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
json = "{ \"android\":"+json+"}";
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
I have found some explanation how to pass data but I am having problem at new AdapterView.OnItemClickListener()
The problem is
oslist.get(+position)
should be
oslist.get(position)
Also you have
private static final String TAG_NAME = "COD"; // key for name is COD
map.put(TAG_NAME, name);
then
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
Intent intent = new Intent(ActivityName.this, YOURACTIVITY.class);
intent.putExtra("key", name);
startActivity(intent);
}
});
Should move setAdapter coe out of for loop
Also change to
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter)
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
String ver = oslist.get(position).get(TAG_VER);
String api = oslist.get(position).get(TAG_API);
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
intent.putExtra("key", name);
intent.putExtra("key1", ver);
intent.putExtra("key2", api);
startActivity(intent);
}
});
}
In Another Activtiy
String name =getIntent().getStringExtra("key");
String api =getIntent().getStringExtra("key1");
String ver =getIntent().getStringExtra("key"2);
You should create a custom adapter. Also create a DataModel which will hold all the 3 values (Version, Name and Api). Make it Serializable.
public class MyModel implements Serializable{
private static final long serialVersionUID = 1L;
String version, name, api;
public MyModel(String modelVer, String modelName, String modelApi){
version = modelVer;
name = modelName ;
api = modelApi;
}
//Add Getters and Setters
}
Instead of creating HashMap<String, String> map = new HashMap<String, String>(); Create
ArrayList<MyModel> modelList = new ArrayList<MyModel>();
then in OnItemClickListener()
//To send data
MyModel modelToPass = modelList.get(position);
intent.putExtra("MyObject", modelToPass);
//To get data
getIntent().getSerializableExtra("MyObject");
for example you can pass the position of item that is clicked by below code
public void onListItemClick(ListView parent, View v, int position,
long id){
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
in YourActivity oncreate() method
Intent current=getIntent();
int position=current.getExtras().getInt("pos");
for sending your data you can make class below
public class Information implements Serializable {
public String BagNumber;
public String COD;
public String OrderNo;
public String SubOrderNo;
......
......
}
and for send it
Information details = new Information ();
details.BagNumber = "";
details.COD = "12";
details.OrderNo = "ff";
....
....
Intent i = new Intent(getApplicationContext(), YourActivity.class);
i.putExtra("inf", details);
startActivity(i);
For receive it
Information model = (Information ) getIntent().getSerializableExtra("inf");
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.