I have made an listview application, then i created a new one with fragments and want to implement listview to fragments. But when i do i got an strange error.
public class Fragment1 extends Fragment {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_row_layout, container, false);
progressbar = (ProgressBar)rootView.findViewById(R.id.progressBar);
String url = "";
new DownloadFilesTask().execute(url);
return rootView;
}
public void updateList() {
feedListView= (ListView)getActivity().findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
**feedListView.setAdapter(new CustomListAdapter(this, feedList));**
feedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
**Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);**
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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 (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("description"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Problems are on this lines
feedListView.setAdapter(new CustomListAdapter(this, feedList));
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
Multiple markers at this line
- Line breakpoint:Fragment1 [line: 57] - updateList()
- The constructor CustomListAdapter(Fragment1, ArrayList<FeedItem>) is
undefined
No enclosing instance of the type FeedListActivity is accessible in scope
CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
in this line feedListView.setAdapter(new CustomListAdapter(this, feedList)); just replace this with getActivity();
Related
I'm making a simple news app for my class and i'm using an api from The Guardian to populate my feed. I had it all working with the article Title, Date, and URL, but upon adding the Section and Author name I cant seem to get it to populate the feed. The device is saying No News Found and the log is saying "Error response code: 429"
Any help/criticism is greatly appreciated!
Activity
public class NewsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private static final String LOG_TAG = NewsActivity.class.getName();
private static final String GUARDIAN_REQUEST_URL =
"http://content.guardianapis.com/search?section=games&order-by=newest&api-key=test&show-tags=contributor";
private static final int NEWS_LOADER_ID = 1;
private NewsAdapter mAdapter;
private TextView mEmptyStateTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_activity);
ListView newsListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
newsListView.setEmptyView(mEmptyStateTextView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
News currentNews = mAdapter.getItem(position);
Uri newsUri = Uri.parse(currentNews.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
startActivity(websiteIntent);
}
});
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_news);
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
updateUi(news);
}
}
private void updateUi(List<News> news) {
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
mAdapter.clear();
}
}
Adapter
public class NewsAdapter extends ArrayAdapter<News> {
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.news_list_item, parent, false);
}
News currentNews = getItem(position);
TextView titleView = (TextView) listItemView.findViewById(R.id.title);
String title = currentNews.getTitle();
titleView.setText(title);
TextView dateView = (TextView) listItemView.findViewById(R.id.date);
String dateToString = String.valueOf(currentNews.getDate());
String date = dateToString.substring(0, 10);
dateView.setText(date);
TextView authorView = (TextView) listItemView.findViewById(R.id.firstname);
String authorFirstName = currentNews.getAuthorFirstName();
authorView.setText(authorFirstName);
TextView lastNameView = (TextView) listItemView.findViewById(R.id.lastname);
String authorLastName = currentNews.getAuthorLastName();
lastNameView.setText(authorLastName);
TextView sectionView = (TextView) listItemView.findViewById(R.id.section);
String section = currentNews.getSection();
sectionView.setText(section);
return listItemView;
}
}
QueryUtils
public class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<News> fetchNewsData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<News> newss = extractResultFromJson(jsonResponse);
return newss;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the news JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<News> extractResultFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> newss = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject mainResponse = baseJsonResponse.getJSONObject("response");
JSONArray newsArray = mainResponse.getJSONArray("results");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject currentNews = newsArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
String section = currentNews.getString("sectionName");
JSONArray tagsArray = currentNews.getJSONArray("tags");
for (int j = 0; j < tagsArray.length(); j++) {
JSONObject currentTag = tagsArray.getJSONObject(j);
String authorFirstName = currentTag.getString("firstName");
String authorLastName = currentTag.getString("lastName");
News news = new News(title, date, url, authorFirstName, authorLastName, section);
newss.add(news);
}
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newss;
}
}
I am working on an application related with news, I have successfully parsed a json response and displayed the data in listview.
But the listview is not loading data at first time and remains empty.
On second time it displayed parsed data in listview.
What might be the problem ? Below is my code
// This is my java file:
public class FunHallListActivity extends AppCompatActivity {
FunHallDBHandler funhallhandler;
SQLiteDatabase db;
InputStream is=null;
String resultFunHall = null;
String line=null;
int code;
String URL = "";
private Context context;
private ListView fhListview;
private FunHallAdapter adapterfunhall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_hall_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
fhListview=(ListView)findViewById(R.id.funhall_lv);
context=this;
new FunHallFetcherTask().execute();
funhallhandler=new FunHallDBHandler(context);
ArrayList<FunHall> fhDataList = new ArrayList<FunHall>();
fhDataList = funhallhandler.getAllFunHall();
adapterfunhall = new FunHallAdapter(context, fhDataList);
fhListview.setAdapter(adapterfunhall);
}
//Json parsing code with to fech and add into Sqlite Database
class FunHallFetcherTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cmr.newsoft.co.in/FunctionalHall.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("pass 1", "connection success ");
Log.d("Data:",is.toString());
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
resultFunHall = sb.toString();
Log.d("Json_string_Result", resultFunHall);
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.d("Fail 2", e.toString());
}
// Log.e(result,"hello");
try
{
JSONArray jArrayFunHall = new JSONArray(resultFunHall);
for(int i=0; i<jArrayFunHall.length();i++)
{
Log.d("jArrayFunHall.length()", ""+jArrayFunHall.length());
JSONObject json_data = jArrayFunHall.getJSONObject(i);
publishProgress();
code=1;
String funhall_Name = json_data.getString("Name");
String funhall_Address = json_data.getString("Address");
String funhall_Phone = json_data.getString("Phone");
FunHall funhall=new FunHall();
funhall.setFHallName(funhall_Name);
funhall.setFHalladdress(funhall_Address);
funhall.setFHallContact(funhall_Phone);
funhallhandler.addFunHall(funhall);
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
//Json Parsing code end
return null;
}
}
}
// and this is my adapter
public class FunHallAdapter extends BaseAdapter {
private List<FunHall> funHallList;
private Context context;
private LayoutInflater layoutInflater;
public FunHallAdapter(Context context, List<FunHall> funHallList)
{
this.context = context;
this.funHallList = funHallList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return funHallList.size();
}
#Override
public FunHall getItem(int position) {
return funHallList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tvfunHallName,tvfunHalladdress,tvfunHallcontact;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Holder holder;
if (convertView == null)
{
holder = new Holder();
convertView = layoutInflater.inflate(R.layout.funhall_list_item,null);
holder.tvfunHallName=(TextView)convertView.findViewById(R.id.funhallname_tv);
holder.tvfunHalladdress=(TextView)convertView.findViewById(R.id.funhalladdress_tv);
holder.tvfunHallcontact=(TextView)convertView.findViewById(R.id.hunhallcantact_tv);
convertView.setTag(holder);
}else
{
holder = (Holder) convertView.getTag();
}
holder.tvfunHallName.setText(funHallList.get(position).getFHallName());
holder.tvfunHalladdress.setText(funHallList.get(position).getFHalladdress());
holder.tvfunHallcontact.setText(funHallList.get(position).getFHallContact());
return convertView;
}
}
i think you must declare setAdapter was onPostExecute. don't declare before onPreExecute or doInBackground. i think it was issue..
Issue is that you are not notifying the adapter when data is changed.
Follow the steps
1. Modify your constructor
ArrayList<FunHall> funHallList;
public FunHallAdapter(Context context, ArrayList<FunHall> funHallList)
{
this.context = context;
this.funHallList = funHallList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Step 2.
In your FunHallAdapter add this method
public void swapData(ArrayList<FunHall> funHallList){
this.funHallList = funHallList;
notifyDataSetChanged();
}
In your FunHallListActivity
class FunHallFetcherTask extends AsyncTask<Void,Void,String> {
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cmr.newsoft.co.in/FunctionalHall.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("pass 1", "connection success ");
Log.d("Data:",is.toString());
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
resultFunHall = sb.toString();
Log.d("Json_string_Result", resultFunHall);
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.d("Fail 2", e.toString());
}
// Log.e(result,"hello");
return resultFunHall ;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!TextUtils.isEmpty(s)) {
try
{
JSONArray jArrayFunHall = new JSONArray(resultFunHall);
for(int i=0; i<jArrayFunHall.length();i++)
{
Log.d("jArrayFunHall.length()", ""+jArrayFunHall.length());
JSONObject json_data = jArrayFunHall.getJSONObject(i);
publishProgress();
code=1;
String funhall_Name = json_data.getString("Name");
String funhall_Address = json_data.getString("Address");
String funhall_Phone = json_data.getString("Phone");
FunHall funhall=new FunHall();
funhall.setFHallName(funhall_Name);
funhall.setFHalladdress(funhall_Address);
funhall.setFHallContact(funhall_Phone);
funhallhandler.addFunHall(funhall);
}
adapterfunhall.swapData(funhallhandler.getAllFunHall());
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
}
i found what mistake i did, and i solved it as follow,
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArrayList<FunHall> fhDataList = new ArrayList<FunHall>();
fhDataList = funhallhandler.getAllFunHall();
adapterfunhall = new FunHallAdapter(context, fhDataList);
fhListview.setAdapter(adapterfunhall);
}
I am using viewpager with gridview and downloading json data into it and implemented gridview scroll listener but whenever i start activity again the current viewpager fragment in which sroll listener implemented shows blank.
Here is my code, please see and tell me my mistake.
//My Activity Fragment
private static String url = "http://--------/------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
//My Json Execution
new LoadData().execute(url);
//Scroll listener when gridview reaches at end
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 10) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//Loading new datas in gridview
new LoadData()
.execute("http://-----/-----");
mLoading = true;
}
}
});
return rootView;
}
private class LoadData extends AsyncTask<String, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//checking whether adapter is null or not
if (adap == null) {
adap = new Grid_View_Adatper(getActivity()
.getApplicationContext(), arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
}
Thanks in advance...
This question already has answers here:
Error parsing data org.json.JSONException: Value String cannot be converted to JSONArray
(2 answers)
Closed 8 years ago.
Here is list activity
ListActivity:
public class ListDataActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_listview);
url = "http://xxx.xx.x.xxx/index.php";
Bundle c = getIntent().getExtras();
blo = c.getString("blood");
new ProgressTask(ListDataActivity.this).execute();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
class ProgressTask extends AsyncTask<String, Void, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(ListDataActivity.this,
MainActivity.class));
}
}
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.row_listitem, new String[] { name, Category },
new int[] { R.id.vehicleType, R.id.vehicleColor }) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_listitem,
null);
}
// TODO Auto-generated method stub
if (position % 2 == 1)
convertView.setBackgroundColor(Color.rgb(120, 151, 66));
else
convertView.setBackgroundColor(Color.rgb(86, 107, 129));
return super.getView(position, convertView, parent);
}
};
setListAdapter(adapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
protected Boolean doInBackground(final String... args) {
url = url + "?blo_name=" + blo;
Log.d("", url);
baseAdapter jParser = new baseAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(name);
String vfuel = c.getString(Category);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(name, vtype);
map.put(Category, vfuel);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
Base Adapter class:
public class baseAdapter {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public baseAdapter() {}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed ");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
PHP:
if (isset($_POST['blo_name'])) {
$str = $_POST['blo_name'];
$sql = "SELECT * FROM blood_group where Category IN ($str)";
$result = mysql_query($sql);
while ($row=mysql_fetch_array($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
}
I am trying to parse bol string, it have value like bol="'B-','O-'"; while I parse this type of value it didn't show results and gives the logcat
logcat:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
I need to get result against query SELECT * FROM blood_group where Category IN ($str) but I cannot get. When I give hard core value in php like $str = "'A+','B+'"; it give me result while parsing from android it does not give result while in logcat I can see value http://xxx.xx.x.xxx/heart.php?blo_name='A','B' but error as well.
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
Notice <br - the web service is returning HTML and not a plain JSON string. Basically you need to fix your PHP response so it doesn't return HTML.
I am trying to load multiple url rss links from a text file. so far it works loading just one link from the file. i tried using a delimiter but it doesn't seem to work. any help is appreciated.
Code
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line) ;
}
String [] arr = rsslink.toString().split(";");
for (int i = 0; i < arr.length; i++)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
And this what the text file looks like with ";" as the delimiter
http://www.engadget.com/rss.xml; http://www.pcworld.com/index.rss; http://feeds.feedburner.com/SpoonForkBacon?format=xml;
RssFragment
public class RssFragment extends Fragment implements OnItemClickListener
{
private ProgressBar progressBar;
private ListView listView;
private View view;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (view == null)
{
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
}
else
{
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
private void startService()
{
Intent intent = new Intent(getActivity(), RssService.class);
intent.putExtra(RssService.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler())
{
#SuppressWarnings("unchecked")
#Override
protected void onReceiveResult(int resultCode, Bundle resultData)
{
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService.ITEMS);
if (items != null)
{
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
}
else
{
Toast.makeText(getActivity(), "An error occured while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
};
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}