Error parsing JSON Array, DOCTYPE - java

ive got a working listview which receives JSON from my DB. But when i try with this link: I get "Error parsing data org.json.JSONException: Value
The JSON output is clean and should work! My activitiy
package com.spxc.ssa.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;
public class ListShowsController extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Shows");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("items");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
map.put("video_id", String.valueOf(i));
map.put("video_title", "" + e.getString("video_title"));
//map.put("season", "Season: " + e.getString("season"));
map.put("video_location", "" + e.getString("video_location"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Intent myIntent = new Intent(ListShowsController.this,
ShowsController.class);
myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("season", o.get("season"));
myIntent.putExtra("video_location", o.get("video_location"));
startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
AsyncTask
package com.spxc.ssa.streaming.task;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class JsonAsync extends AsyncTask<String, Void, JSONObject> {
public interface JsonListener {
public void onObjectReturn(JSONObject object);
}
public void setJsonListener(JsonListener jsonListener) {
mListener = jsonListener;
}
private JsonListener mListener;
public static final String TAG = JsonAsync.class.getSimpleName();
#Override
protected JSONObject doInBackground(String... params) {
// The argument passed into tasks are arrays. So you can pass 0 or more
// arguments, when calling from activity, it's really up to you. They
// just have to be separated by commas. Like this :
// new JsonAsync.execute("thisUrl", "thatUrl", "anotherUrl");
// Although I am only grabbing the first item in the array, by calling
// params[0] below.
JSONObject object = null;
if (params != null && params.length > 0) {
object = JSONfunctions.getJSONfromURL(params[0]);
} else {
Log.e(TAG, "Task needs an argument to be able to retrieve data.");
}
// I return the item out of this method, because it is happening of the
// UI thread, so it can;t update items on the screen. You can work with
// a database from this method. That is actually recommended.
return object;
}
#Override
protected void onPostExecute(JSONObject result) {
// This method can touch UI components without throwing an error.
if (result != null && mListener != null) {
mListener.onObjectReturn(result);
}
super.onPostExecute(result);
}
}
I've never seen this error before! What is the problem?
Any help is much appreciated ! Thanks
EDIT:
My other activity which works:
package com.spxc.ssa.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;
public class ListMoviesController extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Movies");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://strongpixel.com/java/movies.php");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("items");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("name"));
//map.put("date", "Released: " + e.getString("date"));
map.put("path", "" + e.getString("path"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "name", "path" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Intent myIntent = new Intent(ListMoviesController.this,
MoviesController.class);
myIntent.putExtra("name", o.get("name"));
myIntent.putExtra("season", o.get("season"));
myIntent.putExtra("path", o.get("path"));
startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Logcat:
03-12 08:35:18.722: E/log_tag(25208): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
03-12 09:06:52.877: V/CustomViewAbove(26397): Received ACTION_DOWN
03-12 09:06:52.920: V/CustomViewAbove(26397): onInterceptTouch moved to:(30.26232, 662.0), diff:(29.26232, 1.0), mLastMotionX:1.0
03-12 09:06:52.936: V/CustomViewAbove(26397): onInterceptTouch moved to:(73.95948, 663.08905), diff:(72.95948, 0.08905029), mLastMotionX:1.0
03-12 09:06:52.940: V/CustomViewAbove(26397): this slide allowed true dx: 72.95948
03-12 09:06:52.940: V/CustomViewAbove(26397): Starting drag! from onInterceptTouch
03-12 09:06:52.993: V/SlidingMenu(26397): changing layerType. hardware? true
03-12 09:06:53.229: V/SlidingMenu(26397): changing layerType. hardware? false
03-12 09:06:54.214: V/CustomViewAbove(26397): Received ACTION_DOWN
03-12 09:06:54.450: D/dalvikvm(26397): GC_CONCURRENT freed 73K, 7% free 4495K/4812K, paused 3ms+6ms, total 24ms
03-12 09:06:55.025: E/log_tag(26397): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Edit:
I tried the same JSON, but just in a txt file strongpixel.com/java/JSON.txt, this works without any problem, it takes some time to load, but it works.

You can't get it work cause your code can't load proper JSON String. There is only one place where you make download:
JSONfunctions.getJSONfromURL(params[0])
You get the obvious error: JSON object can't be created from string like <!doctype html>. It means that you download HTML data instead of JSON. For simple test you can try next code and you will get the same error:
JSONObject object = new JSONObject("<!DOCTYPE html>");
You can get this wrong response from numerous reasons: wrong request, your fire wall, proxy, even server might return wrong result if you don't specify User-Agent header or doesn't perform authorization. I do recommend using some web debug tools that will help you to handle such situations and make sure that your app receive valid data.
If you are using Windows i would recommend you to use Fiddler, it is free. Here is example how you can setup fiddler for your test device: http://www.cantoni.org/2011/06/28/debug-http-android-fiddler
Anyway there is alternative tools for other operating system.

I got it working! It was a simple and idiotic mistake. The server i was connecting to didnt allow POST so in the adapter i changed Httppost to Httpget

Related

Why this Java page doesent showing my data from this Json?

Hello Guys I received a a big problem in my project. I make the OkHttp request i receive response from server all is perfect. the problem is why i can't display data, i made a model item in xml and listview(this is the required view) and when i acces the page is blank.
Can anyone help me with this issue?
code for page is the following:
package com.example.socceraplication;
import static android.content.ContentValues.TAG;
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.util.ArrayList;
public class TeamInfo extends AppCompatActivity {
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_info);
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(TeamInfo.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name=Liverpool")
.get()
.addHeader("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
String jsonStr=response.body().string();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray records = jsonObj.getJSONArray("records");
// looping through All items
for (int i = 0; i < records.length(); i++) {
JSONObject c = records.getJSONObject(i);
String league = c.getString("league");
String season = c.getString("season");
String name = c.getString("name");
String officialName = c.getString("officialName");
String address = c.getString("address");
String telephone = c.getString("telephone");
String fax = c.getString("fax");
String website = c.getString("website");
String founded = c.getString("founded");
String teamSize = c.getString("teamSize");
String averageAge = c.getString("averageAge");
String foreigners = c.getString("foreigners");
String nationaTeamPlayers = c.getString("nationaTeamPlayers");
String teamValue = c.getString("teamValue");
String venue = c.getString("venue");
String venueCapacity = c.getString("venueCapacity");
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("league",league);
result.put("season",season);
result.put("name",name);
result.put("officialName",officialName);
result.put("address",address);
result.put("telephone",telephone);
result.put("fax",fax);
result.put("website",website);
result.put("founded",founded);
result.put("teamSize",teamSize);
result.put("averageAge",averageAge);
result.put("foreigners",foreigners);
result.put("nationaTeamPlayers",nationaTeamPlayers);
result.put("teamValue",teamValue);
result.put("venue",venue);
result.put("venueCapacity",venueCapacity);
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(TeamInfo.this, resultList,
R.layout.list_item_team, new String[]{ "league","season","name","officialName","address","telephone","fax","website","founded","teamSize","averageAge","foreigners","nationaTeamPlayers","teamValue","venue","venueCapacity"},
new int[]{R.id.league, R.id.season,R.id.name,R.id.officialName,R.id.address,R.id.telephone,R.id.fax,R.id.website,R.id.founded,R.id.teamSize,R.id.averageAge,R.id.foreigners,R.id.nationaTeamPlayers,R.id.teamValue,R.id.venue,R.id.venueCapacity});
lv.setAdapter(adapter);
}
}
}
The enqueue call is asynchronous, which means it queues up work to be run in the background at some point in the future, and when it is complete then it runs the callback you supply (onResponse). This means in your case the order of calls is
Start doInBackground
Add your Http call to the queue
Return from doInBackground
Run onPostExecute
Post empty list to the adapter
... some time later ...
Run the onResponse callback when it gets data
To fix this, you can remove the async task entirely and just queue the work from the main thread, since it already handles actually doing the request in the background.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_info);
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
startRequest();
}
private void startRequest() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//...
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) {
showResult(response);
}
});
}
private void showResult(Response response) {
// show the result here - no need to runOnUiThread
// set the adapter, put text in views, etc from in here
}
If you really want to make the call from your own AsyncTask in the background, you should use the synchronous API, not the asynchronous API. This means calling execute instead of enqueue, like this:
// this MUST run on a background thread or it will block the UI thread
Response response = client.newCall(request).execute();

Java onItemSelectedListener and Spinner not returning Anything

I'm building a currency converter (get from API, dynamically fills lists to create available currencies, select two currencies and return the rate. It seems a right of passage exercise).
I've been trying to get a Spinner to work, but despite my best efforts I can't seem to get the listener to do anything when I select a value from the list. When I do click a value, the logs do return something (see below), but I don't know what it means, and why it's not returning the System.out.println("yay") call I want.
D/OpenGLRenderer: endAllActiveAnimators on 0xa7040980
(DropDownListView) with handle 0x95c21270".
The array adapter is properly filling the spinner list from an ArrayList<string> I get get from API and a JSON Object. The listener code looks correct based on the examples I found on S.O. so far.
I wonder if it's an ordering issue in my code? Or something else.
package com.timlee.currencymate;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity {
// public variables
String uRLResultString = "";
ArrayList <String> currencies = new ArrayList<String>();
Spinner currencyOneSpinner;
Spinner currencyTwoSpinner;
// get data from api
public class DownloadTask extends AsyncTask <String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
uRLResultString += current;
data = reader.read();
}
return uRLResultString;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//System.out.println(result);
//if get current list then run this, else run something else
getCurrencyList();
}
}
//gets the list of currecies
public void getCurrencyList () {
try {
JSONObject jsonObject = new JSONObject(uRLResultString);
String base = jsonObject.getString("base");
String rates = jsonObject.getString("rates");
currencies.add(base);
System.out.println(rates);
JSONObject jSonObj = new JSONObject(rates);
Iterator<String> keys = jSonObj.keys();
while (keys.hasNext()) {
String key = (String)keys.next();
currencies.add(key);
if (jSonObj.get(key) instanceof JSONObject) {
}
}
Collections.sort(currencies, String.CASE_INSENSITIVE_ORDER);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currencies = new ArrayList<String>();
String currencyURL = "http://api.fixer.io/latest?base=AUD";
DownloadTask task = new DownloadTask();
task.execute(currencyURL);
// apply Array Adapter and listener
currencyOneSpinner = (Spinner)findViewById(R.id.spinnerCurrencyOne);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,currencies);
currencyOneSpinner.setAdapter(arrayAdapter);
currencyOneSpinner.setOnItemSelectedListener (new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("yay");
return;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
System.out.println("neyh");
return;
}
});
}
}
You did not set a dropdown view for the adapter. Add this line above setOnItemCLickListener
currencyOneSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
And Since you're using an AsyncTask don't forget to call the below line everytime you update the list.
arrayAdapter.notifyDataSetChanged();
NOTE: You have to initialize the adapter globally.

Connect to MySQL?

I used this code to connect to MySQL using WAMP.
But it doesn't work
package com.first.ismael.material_drawer;
import android.app.Activity;
import android.app.Fragment;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by ismae_000 on 11/20/2015.
*/
public class all_meals extends Fragment {
public ProgressDialog pDialog ;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// url to get all products list
private static String url_all_products = "http://192.168.1.7/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "component";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_TYPE ="type";
ListView lv;
// products JSONArray
JSONArray products = null;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.all,
container, false);
productsList = new ArrayList<HashMap<String, String>>();
lv = (ListView)view.findViewById(R.id.listView2);
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
class LoadAllProducts 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 products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Toast.makeText(getActivity(),"There is nothing",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_NAME},
new int[]{R.id.pid, R.id.name});
// updating listview
lv.setAdapter(adapter);
}
});
}
}
}
I used it in a Fragment.
Please help
If you are using WAMP means using localhost for database MySql. Ip address for localhost should 10.0.2.2 not 192.168.1.7
try to replace
_http://192.168.1.7/get_all_products.php
with
_http://10.0.2.2/get_all_products.php
and check your output get_all_products.php, that's should be json format
read this
- why do we use 10.0.2.2 to connect to local web server instead of using computer ip address in android client
check json format use this
- _http://jsonlint.com

xml parsing app force closes with internet disconnected

It works fine with wifi or 3g but force closes with both disconnected.
I am learning from a tutorial, so am not sure but I believe internet disconnection is considered in the code.
Complete logcat http://pastebin.com/aAEGwfFk
code:
package org.tatvamoksh.tml;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Updates extends ListActivity {
public ArrayList<HashMap<String, String>> mylist;
public ListAdapter adapter;
public ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updates_item);
mylist = new ArrayList<HashMap<String, String>>();
adapter = new SimpleAdapter(this, mylist , R.layout.updates,
new String[] { "event", "notice" },
new int[] { R.id.event_title, R.id.notice });
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
/* lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Updates.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
*/
progressDialog = ProgressDialog.show(Updates.this, "Getting updates", "Please wait...");
new GetDataTask().execute();
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnected())
return true;
return false;
}
private class GetDataTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
// Simulates some delay
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if(isOnline()){
mylist.clear();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(Updates.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("update");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("event", "Event:" + XMLfunctions.getValue(e, "event"));
map.put("notice", "Update: " + XMLfunctions.getValue(e, "notice"));
mylist.add(map);
}
}
else{
Toast.makeText(Updates.this, "No connection..", Toast.LENGTH_LONG).show();
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
setListAdapter(adapter);
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
I did try searching for similar questions, most lead to NullPointerException, debugger didn't catch any(I think)
screenshot of debugger perspective
Remove
Toast.makeText(Updates.this, "No connection..", Toast.LENGTH_LONG).show();
Now in that empty else, make your AsyncTask return another value (eg 2)
else{
return 2;
}
If you move return 1; inside the if(isOnline(), then you can get rid of the else and simply write return 2;, but this is just a matter of readbility.
Then in onPostExecute(), check if the value is 2 then make the Toast.
#Override
protected void onPostExecute(Integer result) {
if (result == 1){
setListAdapter(adapter);
progressDialog.dismiss();
super.onPostExecute(result);
}
else
Toast.makeText(Updates.this, "No connection..", Toast.LENGTH_LONG).show();
}

Errors in Android project

I'm having problems working my way through an old tutorial, essentially i'm trying to pull the data returned in JSON format from www.amazingjobs.co.uk/app/marc/api/candidates/ into a listview.
I literally started learning android/java 24 hours ago so its likely it may be very simple but I just can't quite seem to figure it out, lines with errors are in bold!
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.google.gson.Gson;
public class Searchjobs extends Activity {
// url to make request
private static String url = "http://www.amazingjobs.co.uk/app/marc/api/candidates/";
// JSON Node names
private static final String TAG_RESULTS = "results";
// Jobs JSONArray
JSONArray jobs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchjobs);
Button Searchbutton = (Button) findViewById(R.id.Searchbutton);
Searchbutton.setOnClickListener(searchClick);
}
private OnClickListener searchClick = new OnClickListener() {
public void onClick(View v) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> JobList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl("http://www.amazingjobs.co.uk/app/marc/api/candidates/");
// Getting Array of Contacts
try {
jobs = json.getJSONArray(TAG_RESULTS);
for(int i = 0; i < jobs.length();i++){
JSONObject j = jobs.getJSONObject(i);
String title = j.getString("job_title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Title", title);
JobList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**ListAdapter adapter = new SimpleAdapter(this, JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});**
**ERROR: The constructor SimpleAdapter(new View.OnClickListener(){}, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined**
**setListAdapter(adapter);
The method setListAdapter(ListAdapter) is undefined for the type new View.OnClickListener(){}**
// selecting single ListView item
**ListView lv = getListView();**
**ERROR: The method getListView() is undefined for the type new View.OnClickListener(){}**
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
};
};
EDIT Ok new code is below, errors are, which seems odd because the activity errors relate to an activity that definately exists, have tried restart/clean in eclipse too.
Description Resource Path Location Type
activity_searchjobs cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 47 Java Problem
activity_searchjobs cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 105 Java Problem
Searchbutton cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 48 Java Problem
list_item cannot be resolved or is not a field Searchjobs.java /AmazingJobs/src/app/android/amazingjobs line 83 Java Problem
public class Searchjobs extends ListActivity {
// url to make request
private static String url = "http://www.amazingjobs.co.uk/app/marc/api/candidates/";
// JSON Node names
private static final String TAG_RESULTS = "results";
// Jobs JSONArray
JSONArray jobs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchjobs);
Button Searchbutton = (Button) findViewById(R.id.Searchbutton);
Searchbutton.setOnClickListener(searchClick);
}
private OnClickListener searchClick = new OnClickListener() {
public void onClick(View v) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> JobList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl("http://www.amazingjobs.co.uk/app/marc/api/candidates/");
// Getting Array of Contacts
try {
jobs = json.getJSONArray(TAG_RESULTS);
for(int i = 0; i < jobs.length();i++){
JSONObject j = jobs.getJSONObject(i);
String title = j.getString("job_title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Title", title);
JobList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(getApplication(), JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
};
};
You need to extend ListActivity not Activity to make methods like getListView() avaialable or just replace it with findViewById() if you do not want to use ListActivity (it's not mandatory).
ListAdapter adapter = new SimpleAdapter(this, JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});
should be changed to:
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), JobList,R.layout.list_item,
new String[] { "Title" }, new int[] {R.id.title});
Second,
ListView lv = getListView();
will be resolved if you extend ListActivity instead of Activity.

Categories

Resources