Во время выполнения кода (приведенного после сообщения об ошибке) выдается ошибка как
Кодирование следующее:
public class Slide extends ActionBarActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> detailsList; //Creating a Arraylist
private static String URL = "URL to my php page";
private static final String TAG_DETAILS = "details";
private static final String TAG_TITLE = "title";
JSONArray details = null;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide);
new onlineload().execute();
}
class onlineload extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Slide.this);
pDialog.setMessage("Fetching Books...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String title = "";
TextView tvTitle = (TextView)findViewById(R.id.Title);
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
Log.d("All Products:",json.toString());
try {
details = json.getJSONArray(TAG_DETAILS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
title = title + c.getString(TAG_TITLE)+"\n";
tvTitle.setText(title);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Показанный выше мой код Java ..
Функция этого кода — получить название книги (в базе данных доступно более 10 книг) из онлайн-базы данных и просмотреть ее в виде прокрутки.
мой PHP-код работает, я получаю вывод только проблема в отображении его в активности Android!
Нужна помощь!
JSON-код:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
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
Log.d("Entered Get", "Get SUccess"+url+method);
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 object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Agree with @ρяσѕρєя K
There was cast exception occurred that means you need to use JSON Array. Coz you are using JSON Object where actually JSON Array is required.
If you are confused within response which is receiving is JSONArray or JSONObject then you can go for get() method which return data in Object manner.
example : Object c = details.get(i);
So after that you can check for
If(c instanceOf JSONArray){
/// perform as array operation
}If(c instanceOf JSONObject){
// perform json object retrieving operation
}
Других решений пока нет …