please help me with this problem..
i change my previous question to this..
i cant post new question because im in danger of being blocked..
heres my problem..
im trying to get data from database but i got this error when i run the app..
09-29 13:41:07.032 26507-26507/? E/Error﹕ No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ org.json.JSONException: No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:548)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:249)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:233)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5494)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.042 26507-26507/? I/MemoryCache﹕ MemoryCache will use up to 24.0MB
09-29 13:41:07.042 26507-26507/? D/AndroidRuntime﹕ Shutting down VM
09-29 13:41:07.042 26507-26507/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418e38e0)
09-29 13:41:07.042 26507-26507/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.ListViewAdapter.getCount(ListViewAdapter.java:38)
at android.widget.ListView.setAdapter(ListView.java:463)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:236)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5494)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.052 941-7799/? I/ActivityManager﹕ Notify an ApplicationCrash
here is the code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
NEW ERROR
09-29 14:12:26.981 593-593/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)
09-29 14:12:26.992 593-593/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:259)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:232)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:179)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
this is line 259
arraylist.add(map);
line 232
prepareListData();
UPDATED CODE
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
the image is not displaying when i use the .php file in this code..
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
but when i use the .txt file it works..
i tried to copy the data of products.php and save it as .txt then when i change the link to this http://joehamirbalabadan.com/android/android/products.txt..
it works.. but i want to use the .php file because i use this to get the data from database..
products.php result
products.txt result
please help me..
Try to initialize arraylist first and also create HashMap item new instance inside for loop like :
protected void prepareListData(){
try {
arraylist = new ArrayList<HashMap<String, String>>();
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
Initialize your result string with products like this one:
static final String result="products";
It will work
I think you need to decalre below variables
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
which you have to change like this
public static final String result="result";
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
I hope it work.
Related
I have a viewPager to appear 3 fragments, the first is a ListFragment, this is the code:
MainActivity's code:
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "My interventions", "MAP", "My report" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
FragmentList's code:
package info.androidhive.tabsswipe;
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.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class TopRatedFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_top_rated,
container, false);
return myFragmentView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
ArrayList<HashMap<String, String>> interventionsList;
// Progress Dialog
private ProgressDialog pDialog;
// url to get all interventions list
private static String url_all_interventions = "http://10.0.2.2/Scripts/liste_interventions.php";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// interventions JSONArray
JSONArray interventions = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.getListView().setTextFilterEnabled(true);
// Hashmap for ListView
interventionsList = new ArrayList<HashMap<String, String>>();
// Loading interventions in Background Thread
new LoadAllInterventions().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllInterventions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading interventions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONArray json = jParser.makeHttpRequest(url_all_interventions, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Interventions: ", json.toString());
try {
// Getting Array of interventions
JSONArray interventions = json;
// looping through All interventions
for (int i = 0; i < interventions.length(); i++) {
JSONObject c = interventions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String name = c.getString("name");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("Int_id", id);
map.put("Int_name", name);
// adding HashList to ArrayList
interventionsList.add(map);
}
} catch (JSONException e) {e.printStackTrace();}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), interventionsList,
R.layout.list_item, new String[] { "Int_id",
"Int_name"},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
Log.e("LIST", "setListAdapter is done");
}
});
}
}
public void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}
}
this is the JSONParser class's code:
package info.androidhive.tabsswipe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jArr = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONArray makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON array
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jArr;
}
}
this is the class TabsPagerAdapter's code:
package info.androidhive.tabsswipe.adapter;
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
and this is MoviesFragment's code: "Edited"
package info.androidhive.tabsswipe;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MoviesFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button ajout=(Button)getActivity().findViewById(R.id.button1);
ajout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText code=(EditText)getActivity().findViewById(R.id.editText1);
EditText lib=(EditText)getActivity().findViewById(R.id.editText2);
EditText desc=(EditText)getActivity().findViewById(R.id.editText3);
EditText st=(EditText)getActivity().findViewById(R.id.editText4);
EditText act=(EditText)getActivity().findViewById(R.id.editText5);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
StringBuffer adresse= new StringBuffer("http://10.0.2.2:8080/Scripts/Create_Rapport.php?");
adresse.append("code="+code.getText().toString());
adresse.append("&lib="+lib.getText().toString());
adresse.append("&desc="+desc.getText().toString());
adresse.append("&state="+st.getText().toString());
adresse.append("&action="+act.getText().toString());
getPage(adresse.toString());
}});
}
public void getPage(String adresse) {
new Requete().execute(adresse);
}
private class Requete extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
}
catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
}
When i run the application, first the first fragment which containt the list populated from the database appear and no data in the fragment, when i swipe from this fragment to an other fragment, the application close and this error appear on the LogCat:
D/All Interventions:(1066): [{"id":"2","name":"request 2"},{"id":"1","name":"request 1"}]
10-26 16:53:54.677:
I/Choreographer(1066): Skipped 122 frames! The application may be doing too much work on its main thread.
10-26 16:54:13.732:
D/AndroidRuntime(1066): Shutting down VM
10-26 16:54:13.737:
W/dalvikvm(1066): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-26 16:54:13.887:
E/AndroidRuntime(1066): FATAL EXCEPTION: main
10-26 16:54:13.887:
E/AndroidRuntime(1066): java.lang.NullPointerException
10-26 16:54:13.887:
E/AndroidRuntime(1066): at info.androidhive.tabsswipe.MoviesFragment.onActivityCreated(MoviesFragment.java:26)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1486)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:550)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:509)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:490)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at info.androidhive.tabsswipe.MainActivity.onTabSelected(MainActivity.java:70)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:579)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1081)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:519)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.view.View.performClick(View.java:4204)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.view.View$PerformClick.run(View.java:17355)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.os.Handler.handleCallback(Handler.java:725)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.os.Looper.loop(Looper.java:137)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-26 16:54:13.887
This is MovieFragment's code, please what is the error's cause ??
package info.androidhive.tabsswipe;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MoviesFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button ajout=(Button)getActivity().findViewById(R.id.button1);
ajout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText code=(EditText)getActivity().findViewById(R.id.editText1);
EditText lib=(EditText)getActivity().findViewById(R.id.editText2);
EditText desc=(EditText)getActivity().findViewById(R.id.editText3);
EditText st=(EditText)getActivity().findViewById(R.id.editText4);
EditText act=(EditText)getActivity().findViewById(R.id.editText5);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
StringBuffer adresse= new StringBuffer("http://10.0.2.2:8080/Scripts/Create_Rapport.php?");
adresse.append("code="+code.getText().toString());
adresse.append("&lib="+lib.getText().toString());
adresse.append("&desc="+desc.getText().toString());
adresse.append("&state="+st.getText().toString());
adresse.append("&action="+act.getText().toString());
getPage(adresse.toString());
}});
}
public void getPage(String adresse) {
new Requete().execute(adresse);
}
private class Requete extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
}
catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
}
hi i want to download a json file from my server and add this json to list view i handle this on fragment with asyncktask method and list adapter
but i get this error
10-27 14:45:30.385: E/AndroidRuntime(2074): FATAL EXCEPTION: main
10-27 14:45:30.385: E/AndroidRuntime(2074): java.lang.NullPointerException
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.mihanServer.Fragments.NewsFragment$JsonReader.onPostExecute(NewsFragment.java:89)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.mihanServer.Fragments.NewsFragment$JsonReader.onPostExecute(NewsFragment.java:1)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask.finish(AsyncTask.java:631)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.Handler.dispatchMessage(Handler.java:99)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.Looper.loop(Looper.java:137)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-27 14:45:30.385: E/AndroidRuntime(2074): at java.lang.reflect.Method.invokeNative(Native Method)
10-27 14:45:30.385: E/AndroidRuntime(2074): at java.lang.reflect.Method.invoke(Method.java:511)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-27 14:45:30.385: E/AndroidRuntime(2074): at dalvik.system.NativeStart.main(Native Method)
this is my fragment code
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mihanServer.sedasema.CustomListAdapter;
import com.mihanServer.sedasema.JSONParser;
import com.mihanServer.sedasema.MainActivity;
import com.mihanServer.sedasema.News;
import com.mihanServer.sedasema.R;
import android.app.ProgressDialog;
import android.database.DataSetObservable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ListView;
public class NewsFragment extends Fragment {
private static final String url = "http://192.168.1.6/web/app_dev.php/news/list";
private List<News> newsList = new ArrayList<News>();
private ListView listView;
private CustomListAdapter adapter;
private JSONArray jArray;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news , container, false);
listView = (ListView)rootView.findViewById(R.id.list);
try
{
adapter = new CustomListAdapter(getActivity(),newsList);
listView.setAdapter(adapter);
}
catch(Exception ex)
{
ex.printStackTrace();
}
new JsonReader().execute();
return rootView;
}
public class JsonReader extends AsyncTask<String, String, JSONObject>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
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 {
// Getting JSON Array
jArray = json.getJSONArray("news");
for (int i = 0; i < jArray.length(); i++) {
try {
News news = new News();
JSONObject obj = jArray.getJSONObject(i);
news.setNewsTitle(obj.getString("title"));
news.setNewsThumbnailUrl(obj.getString("thumbnail"));
news.setNewsReleaseTime( obj.getString("created"));
news.setNewsBody(obj.getString("body"));
news.setNewsId(obj.getInt("id"));
// adding app to app array
newsList.add(news);
}
catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
catch (JSONException ex){
ex.printStackTrace();
}
}
}
}
after line notify data set changed i get error.
this is my list adapter code
import com.mihanServer.sedasema.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.mihanServer.sedasema.MainActivity;
import com.mihanServer.sedasema.AppController;
import com.mihanServer.sedasema.News;
public class CustomListAdapter extends BaseAdapter {
private final Activity actitity;
private LayoutInflater inflater;
private List<News> newsItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
News news;
public CustomListAdapter(Activity activity,List<News> newsItems) {
this.newsItems = newsItems;
this.actitity =activity;
imageLoader = new AppController().getImageLoader();
}
#Override
public int getCount() {
return newsItems.size();
}
#Override
public Object getItem(int location) {
return newsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
//inflater = (LayoutInflater) activity
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_list, null);
//comment for image reading
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView newsthumbnail = (NetworkImageView) convertView
.findViewById(R.id.news_image);
TextView newsTitle = (TextView) convertView.findViewById(R.id.news_title);
//TextView newsBody = (TextView) convertView.findViewById(R.id.news_body);
TextView newsReleaseTime = (TextView) convertView.findViewById(R.id.news_release_time);
// getting news data for the row
news = newsItems.get(position);
//comment for image reading
newsthumbnail.setImageUrl(news.getNewsThumbnailUrl(), imageLoader);
newsTitle.setText(news.getNewsTitle());
newsReleaseTime.setText( news.getNewsReleaseTime());
//newsBody.setText(news.getNewsBody());
convertView.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
news=newsItems.get(position);
Intent intent = new Intent(actitity.getApplicationContext(),NewsDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",news.getNewsTitle());
intent.putExtra("body", news.getNewsBody());
intent.putExtra("newsimage", news.getNewsThumbnailUrl());
intent.putExtra("releasedtime", news.getNewsReleaseTime());
actitity.getApplicationContext().startActivity(intent);
}
});
return convertView;
}
}
and this is my json parser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
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 = "";
static Socket socket = null;
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try{
//try {
//URL urlS = new URL(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*catch (UnknownHostException e) {
e.printStackTrace();
json = "UnknownHostException: " + e.toString();
}*/
//is = urlS.openStream();
//}
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 = json.replace(""", "\"");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
}/*catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
json = "IOException: " + e.toString();*/
// }
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return jObj;
}
}
i also use volley lib for download images like this
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
try with below changes in your adapter class:
public class CustomListAdapter extends BaseAdapter {
private final Activity actitity;
private LayoutInflater inflater;
private List<News> newsItems;
private AQuery aQuery;
//ImageLoader imageLoader = AppController.getInstance().getImageLoader();
News news;
public CustomListAdapter(Activity activity,List<News> newsItems) {
this.newsItems = newsItems;
this.actitity =activity;
aQuery=new AQuery(activity);
// imageLoader = new AppController().getImageLoader();
}
#Override
public int getCount() {
return newsItems.size();
}
#Override
public Object getItem(int location) {
return newsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
//inflater = (LayoutInflater) activity
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_list, null);
//comment for image reading
/*if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();*/
NetworkImageView newsthumbnail = (NetworkImageView) convertView
.findViewById(R.id.news_image);
TextView newsTitle = (TextView) convertView.findViewById(R.id.news_title);
//TextView newsBody = (TextView) convertView.findViewById(R.id.news_body);
TextView newsReleaseTime = (TextView) convertView.findViewById(R.id.news_release_time);
// getting news data for the row
news = newsItems.get(position);
if(news.getNewsThumbnailUrl().length()>0){
aQuery.id(newsthumbnail).image(news.getNewsThumbnailUrl(),true,true);
}else{
newsthumbnail.setVisibility(View.GONE);
}
//comment for image reading
//newsthumbnail.setImageUrl(news.getNewsThumbnailUrl(), imageLoader);
newsTitle.setText(news.getNewsTitle());
newsReleaseTime.setText( news.getNewsReleaseTime());
//newsBody.setText(news.getNewsBody());
convertView.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
news=newsItems.get(position);
Intent intent = new Intent(actitity.getApplicationContext(),NewsDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",news.getNewsTitle());
intent.putExtra("body", news.getNewsBody());
intent.putExtra("newsimage", news.getNewsThumbnailUrl());
intent.putExtra("releasedtime", news.getNewsReleaseTime());
actitity.getApplicationContext().startActivity(intent);
}
});
return convertView;
}
}
Hie Friends
I have one ListView which displays image data from JSON parser for that I use Custom Base Adapter.
But I got following exception.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:193)
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
My Code Is:
package com.example.ecard;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.loopj.android.image.SmartImageView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ECard_main extends Activity
{
String catagories;
String anim_id,album_id,anim_name,anim_thumb,anim_url;
TextView title;
SmartImageView image;
ListView hlv;
ArrayList<HashMap<String, String>> albumList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.ecard_main);
Intent i=getIntent();
catagories=i.getExtras().getString("Catagories");
title=(TextView)findViewById(R.id.tv_main_title);
image=(SmartImageView)findViewById(R.id.IV_image);
title.setText(catagories);
//hlv = getListView();
hlv = (ListView) findViewById(android.R.id.list);
albumList = new ArrayList<HashMap<String, String>>();
new AsycLove().execute();
}
class AsycLove extends AsyncTask<String, String, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(ECard_main.this);
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... aurl)
{
try
{
HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/smartecard/love.php");
BufferedReader bufferedReader = null;
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
response = client.execute(postMethod);
final int statusCode = response.getStatusLine().getStatusCode();
Log.v("Album ::","Response:::--->"+response.toString());
Log.v("Album ::","Status Code:::--->"+statusCode);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
//-------------CONVERT DATA TO JSON---------------------------------
try
{
String myjsonstring = stringBuffer.toString();
JSONArray jsonArray = new JSONArray(myjsonstring);
JSONObject jsonObj = null;
albumList.clear();
jsonObj = jsonArray.getJSONObject(0);
for(int i=0; i<jsonArray.length();i++)
{
jsonObj = jsonArray.getJSONObject(i);
anim_id = jsonObj.getString("animation_id");
album_id = jsonObj.getString("album_id");
anim_name = jsonObj.getString("animation_name");
anim_thumb= jsonObj.getString("animation_thumb");
anim_url = jsonObj.getString("animation_url");
anim_url=anim_url.replaceAll("\"","");
Log.v("Anim URL","Anim URL::"+anim_url);
Log.v("Anim Name","Anim Name::"+anim_name);
HashMap<String, String> tmp_album = new HashMap<String, String>();
tmp_album.put("anim_id", anim_id);
tmp_album.put("anim_thumb", anim_thumb);
albumList.add(tmp_album);
}
}
catch (Exception e)
{
Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
e.printStackTrace();
}
}
catch (IOException e)
{
Log.v("Exception: Get get Album in List","Name-"+e.toString());
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String code)
{
Toast.makeText(getApplicationContext(), "Image URL Call Successfully", Toast.LENGTH_LONG).show();
Log.v("Album","Album List::"+albumList);
ECard_main_Custom_Adapter adapter =new ECard_main_Custom_Adapter(getApplicationContext(),albumList);
hlv.setAdapter(adapter);
progressDialog.dismiss();
progressDialog = null;
}
}
}
And My Adapter Is:
import java.util.ArrayList;
import java.util.HashMap;
import com.loopj.android.image.SmartImageView;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ECard_main_Custom_Adapter extends BaseAdapter
{
private Context context;
ArrayList<HashMap<String, String>> listAlbum;
ViewHolder vholder;
Drawable image;
public ECard_main_Custom_Adapter(Context context, ArrayList<HashMap<String, String>> albumList)
{
this.context = context;
this.listAlbum=albumList;
}
#Override
public int getCount()
{
Log.v("1","1");
return listAlbum.size();
}
#Override
public Object getItem(int position)
{
Log.v("1","2");
return position;
}
#Override
public long getItemId(int position)
{
Log.v("1","3");
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Log.v("1","1");
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
vi = inflater.inflate(R.layout.ecard_main_adapter, null);
vholder = new ViewHolder();
vholder.img_album=(SmartImageView)vi.findViewById(R.id.IV_image);
vi.setTag(vholder);
try
{
String anim_id=listAlbum.get(position).get("anim_id");
String url=listAlbum.get(position).get("anim_thumb");
Log.v("Anim ID and Anim URL","Id:"+anim_id+" URL:"+url);
vholder.img_album.setImageUrl(url);
}
catch (Exception e)
{
// TODO: handle exception
Log.v("Error Ecard","Error is:::"+e);
}
return vi;
}
static class ViewHolder
{
SmartImageView img_album;
}
}
Please tell me where I am wrong.
Any help is appreciated.
Thanks In advance.
First correct this
hlv = (ListView) findViewById(android.R.id.list);
to
hlv = (ListView) findViewById(R.id.list);
It might cause an error. and make sure your ecard_main.xml layout contains ListView with id list
I'm just new to android and java and i m trying to build a sample android application.
I picked up application view from androhive looks like google+ app
and made my function following to many tutorials online
but i'm unable to integrate them.
here are my codes
Here is my fragment sample which is used in switching activity using sidebar
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MHEFragment extends Fragment {
public MHEFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Heres my function os listview
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private String jsonResult;
private String url = "http://192.168.129.1/1.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("story");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("story_name");
String number = jsonChildNode.getString("story_id").toString();
String outPut = number + "-" + name;
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View name, int position,
long number) {
Intent intnt = new Intent(getApplicationContext(), Tester.class);
String deta = adapter.getItemAtPosition(position).toString();
String myStr = deta.replaceAll( "[^\\d]", "" );
intnt.putExtra(EXTRA_MESSAGE,myStr);
startActivity(intnt);
}
});
storyList.add(createStory("stories", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
android.R.layout.simple_list_item_1,
new String[] { "stories" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createStory(String name, String number) {
HashMap<String, String> storyNameNo = new HashMap<String, String>();
storyNameNo.put(name, number);
return storyNameNo;
}
}
How can i integrate my listview in above fragment?
If you want ListView in fragment then you'd be better off using your Fragment which would subclass ListFragment.
And the onCreateView() from ListFragment will return a ListView that you can populate.
http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments
For Fragments, if you want a separate ListView and more in one fragment, it'l help if you go through:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..for what is more to the layout and calling onCreateView()
Also, (not a part of the question, but from & for your code) if it helps, i'd suggest
Use a for each loop where you can instead of for(;;)
(in your case at: for each json child node in json main node)
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?
I am relatively new to Android and working with an online API. I have two activities. The first activity is bringing up a list of search results and placing them into a ListView. This is not a problem. I am trying to select an item from this ListView and pass it to the next activity and fill another ListView in this new activity with information from the selected item. This is where the problem is. The second activity never loads. What is a good way to get the second activity to work? I have been doing research and not getting the desired results. The code for the two activities and helper class are below.
Thank you
The first activity
import helper.ArtistCalendarHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import services.XMLParser;
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 ArtistsSearchActivity extends ListActivity {
public static final String TAG = "ArtistsSearchActivity";
public static final String INTENT_EXTRAS_XML = "XML";
static final String KEY_ARTISTS = "artist";
static final String KEY_ID = "id";
static final String KEY_DISPLAY_NAME = "displayName";
static final String KEY_URI = "uri";
static final String KEY_ON_TOUR_UNTIL = "onTourUntil";
String onTourUntil ;
String displayName;
String identification;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artists_search);
String xml = getIntent().getStringExtra(HomeActivity.INTENT_EXTRAS_XML);
List<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
addArtistsToHashmap(menuItems, xml);
addItemsToList(menuItems);
}
private void addItemsToList(List<HashMap<String, String>> menuItems) {
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item_artist_search, new String[] { KEY_ID, KEY_DISPLAY_NAME,
KEY_URI, KEY_ON_TOUR_UNTIL }, new int[] { R.id.tvId,
R.id.tvDisplayName, R.id.tvUri, R.id.tvOnTourUntil });
setListAdapter(adapter);
}
private void addArtistsToHashmap(List<HashMap<String, String>> menuItems,
String xml) {
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_ARTISTS);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, e.getAttribute(KEY_ID));
map.put(KEY_DISPLAY_NAME, e.getAttribute(KEY_DISPLAY_NAME));
map.put(KEY_URI, e.getAttribute(KEY_URI));
map.put(KEY_ON_TOUR_UNTIL, e.getAttribute(KEY_ON_TOUR_UNTIL));
menuItems.add(map);
}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
displayName = ((TextView) view.findViewById(R.id.tvDisplayName)).getText().toString();
onTourUntil = ((TextView) view.findViewById(R.id.tvOnTourUntil)).getText().toString();
identification = ((TextView) view.findViewById(R.id.tvId)).getText().toString();
new AsyncDownload().execute(identification);
}
});
}
private class AsyncDownload extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ArtistsSearchActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Log.v(TAG, "query is" + params[0]);
String result = new ArtistCalendarHelper().getXml(params[0]);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
pDialog.dismiss();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
Log.v(TAG, "result=" + result);
Intent intent = new Intent();
intent.setClass(ArtistsSearchActivity.this, SingleArtistActivity.class);
intent.putExtra(KEY_DISPLAY_NAME, displayName);
intent.putExtra(KEY_ID, identification);
intent.putExtra(KEY_ON_TOUR_UNTIL, onTourUntil);
intent.putExtra(INTENT_EXTRAS_XML, result);
startActivity(intent);
}
}
}
The second activity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import services.XMLParser;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class SingleArtistActivity extends ListActivity {
public static final String TAG = "SingleArtistActivity";
public static final String INTENT_EXTRAS_XML = "XML";
static final String KEY_VENUE = "event";
static final String KEY_VENUE_NAME = "displayName";
static final String KEY_DISPLAY_NAME = "displayName";
static final String KEY_ON_TOUR_UNTIL = "onTourUntil";
static final String KEY_ID = "id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_artist);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String displayName = in.getStringExtra(KEY_DISPLAY_NAME);
String onTourUntil = in.getStringExtra(KEY_ON_TOUR_UNTIL);
String id = in.getStringExtra(KEY_ID);
// Displaying all values on the screen
TextView lblDisplayName = (TextView) findViewById(R.id.display_name_label);
TextView lblOnTourUntil = (TextView) findViewById(R.id.on_tour_until_label);
TextView lblID = (TextView) findViewById(R.id.id_label);
lblDisplayName.setText(displayName);
lblOnTourUntil.setText(onTourUntil);
lblID.setText(id);
String xml = getIntent().getStringExtra(HomeActivity.INTENT_EXTRAS_XML);
List<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
addItemsToList(menuItems);
addCalendarToHashmap(menuItems, xml);
}
private void addItemsToList(List<HashMap<String, String>> menuItems) {
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item_artist_calendar, new String[] { KEY_VENUE_NAME }, new int[] { R.id.calendarDisplayName });
setListAdapter(adapter);
}
private void addCalendarToHashmap(List<HashMap<String, String>> menuItems,
String xml) {
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_VENUE);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_VENUE_NAME, e.getAttribute(KEY_VENUE_NAME));
menuItems.add(map);
}
}
}
And the my helper class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class LocationCalendarHelper {
private static final String TAG = "LocationCalendarHelper";
private static final String SONGKICK_URL = "http://api.songkick.com/api/3.0/metro_areas/";
private static final String API_KEY = "yIekMi1hQzcFheKc";
public String getXml(String searchQuery) {
HttpClient httpclient = new DefaultHttpClient();
String getParameters = "";
try {
getParameters = URLEncoder.encode(searchQuery, "UTF-8")
+ "/calendar.xml?apikey=" + URLEncoder.encode(API_KEY, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String url = SONGKICK_URL + getParameters;
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i(TAG, response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
My log cat errors. It starts with a bunch of xml so the activity is pulling in the information then ends with an error
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <identifier mbid="eb558587-e7a1-4f2b-9fda-b6ff5e137ed1" href="http://api.songkick.com/api/3.0/artists/mbid:eb558587-e7a1-4f2b-9fda-b6ff5e137ed1.xml"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </artist>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </performance>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <performance billingIndex="3" displayName="Love And Death" billing="support" id="32720419">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <artist displayName="Love And Death" uri="http://www.songkick.com/artists/286472-love-and-death?utm_source=19089&utm_medium=partner" id="286472">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <identifier mbid="27796970-8f7a-4196-9f7d-87f091af4412" href="http://api.songkick.com/api/3.0/artists/mbid:27796970-8f7a-4196-9f7d-87f091af4412.xml"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <identifier mbid="c29b667e-9895-41d2-b5a5-1817050ce0bc" href="http://api.songkick.com/api/3.0/artists/mbid:c29b667e-9895-41d2-b5a5-1817050ce0bc.xml"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </artist>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </performance>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <venue displayName="Rostraver Ice Garden Arena" lat="40.1981235" lng="-79.8294916" uri="http://www.songkick.com/venues/51599-rostraver-ice-garden-arena?utm_source=19089&utm_medium=partner" id="51599">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <metroArea displayName="Belle Vernon" uri="http://www.songkick.com/metro_areas/56020-us-belle-vernon?utm_source=19089&utm_medium=partner" id="56020">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <state displayName="PA"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <country displayName="US"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </metroArea>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </venue>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <start time="19:30:00" datetime="2013-05-15T19:30:00-0500" date="2013-05-15"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <location lat="40.1981235" lng="-79.8294916" city="Belle Vernon, PA, US"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </event>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <event type="Festival" status="ok" displayName="Rock on the Range 2013" uri="http://www.songkick.com/festivals/8261/id/14745014-rock-on-the-range-2013?utm_source=19089&utm_medium=partner" popularity="0
05-10 07:09:41.637: I/Choreographer(796): Skipped 49 frames! The application may be doing too much work on its main thread.
05-10 07:09:43.807: E/Trace(871): error opening trace file: No such file or directory (2)
05-10 07:09:45.357: E/Trace(910): error opening trace file: No such file or directory (2)
05-10 07:09:45.687: E/Trace(923): error opening trace file: No such file or directory (2)
05-10 07:09:46.307: E/Trace(936): error opening trace file: No such file or directory (2)
05-10 07:09:47.167: E/Trace(949): error opening trace file: No such file or directory (2)
05-10 07:09:48.337: E/Trace(975): error opening trace file: No such file or directory (2)
I have an update. The above code works! I will leave it for those that need it. The problem I am having is that if the xml string is too long the search times out. So how do I give Android more time to do its search?
private void addItemsToList(List<HashMap<String, String>> menuItems) {
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item_artist_calendar, new String[] { KEY_VENUE_NAME }, new int[] { R.id.calendarDisplayName });
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}