So I have this code, which is a page with a ListView search field and a button to confirm the search, when the button is pressed the ListView is filled with movie names from the Rotten Tomatoes API, The problem is that someone helped me with this code, and I would love some help breaking it down and understanding it sentence after sentence, My main goal is to get is to get the "title", "synopsis" and "url image" of a movie that was clicked in the list, and pass it with an intent to my other activity but the whole JSON and get specific data stuff, got me very confused.
Link to Rotten Tomatoes API documentation, this is my code:
public class MovieAddFromWeb extends Activity implements View.OnClickListener,
OnItemClickListener {
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public List<String> movieTitles;
static final int ACTIVITY_WEB_ADD = 3;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65aw435cab9rbzsq";
// the number of movies to show in the list
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
}
see the modified code below..
public class MovieAddFromWeb extends Activity implements View.OnClickListener, OnItemClickListener {
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public List<String> movieTitles;
//added new variables
public List<String> movieSynopsis;
public List<String> movieImgUrl;
static final int ACTIVITY_WEB_ADD = 3;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65aw435cab9rbzsq";
// the number of movies to show in the list
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
//newly added
movieSynopsis = new ArrayList<String>();
movieImgUrl= new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
movieSynopsis.add(movie.getString(#add the synopsis var name returned by the JSON));
movieImgUrl.add(movie.getString(#add the urlvar name returned by the JSON));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
//newly added
openMovieEditor.putExtra("movieSynopsis", movieSynopsis.get(position));
openMovieEditor.putExtra("movieImgUrl", movieImgUrl.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
Related
I know this question keeps popping up but my code is slightly different from the other ones, so I don't know where I need to make my changes.
I want to put data ("fest_name") into an ArrayList ("festivals") and make it appear in a ListView.
This is my code for JSON:
public void getFestivals() {
Thread thread_getdata = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
String link = "http://pou-pou.de/stagedriver/android/uebersicht.php";
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
final ArrayList<String> festivals = new ArrayList<String>();
Log.i("Response", "Response : " + response);
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
final String fest_name = jsonobj.getString("fest_name");
festivals.add(fest_name);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread_getdata.start();
}
And this is for the ListView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fahrt_anbieten1);
ListView lvFestivals = (ListView) findViewById(R.id.lvFestivals);
getFestivals();
ListAdapter festivalsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, festivals);
lvFestivals.setAdapter(festivalsAdapter);
}
I just don't know how to combine the two ones: if I run the app, I just get an empty page, but no real errors.
I would be so happy if anyone could help!
First, using Thread to make network requests isn't recommended.
Second, Apache HTTP has some extra code around simple network requests. When you could instead use Volley (you'll need compile 'com.android.volley:volley:1.0.0')
If you implement the below code, you should get something like this listview.
public class FestListActivity extends AppCompatActivity
implements Response.Listener<JSONArray>, Response.ErrorListener {
private ListView mListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(android.R.layout.list_content);
mListView = (ListView) findViewById(android.R.id.list);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
getFestivals();
}
private void getFestivals() {
String festURL = "http://pou-pou.de/stagedriver/android/uebersicht.php";
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest req = new JsonArrayRequest(festURL, this, this);
queue.add(req);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
#Override
public void onResponse(JSONArray response) {
mAdapter.clear();
try {
for (int i = 0; i < response.length(); i++) {
final JSONObject festObj = response.getJSONObject(i);
int festId = Integer.valueOf(festObj.getString("id_fest"));
String festName = festObj.getString("fest_name");
mAdapter.add(festId + " - " + festName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
After the adapter is not a problem if you put the loop
public void getFestivals() {
Thread thread_getdata = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
String link = "http://pou-pou.de/stagedriver/android/uebersicht.php";
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
final ArrayList<String> festivals = new ArrayList<String>();
Log.i("Response", "Response : " + response);
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
final String fest_name = jsonobj.getString("fest_name");
festivals.add(fest_name);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
ListAdapter festivalsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, festivals);
lvFestivals.setAdapter(festivalsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread_getdata.start();
}
Put it on the ListView variable OnCreate
ListView lvFestivals;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fahrt_anbieten1);
lvFestivals = (ListView) findViewById(R.id.lvFestivals);
getFestivals();
}
I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button nothing show up in Listview !!
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
SupportActivity.java
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aaa/getticket.php";
private RequestQueue requestQueue1;
int i ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("error")) {
Toast.makeText(supportActivity.this, "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject ticket ;
JSONArray jsonArray = new JSONArray("responseticket");
ticket = jsonArray.getJSONObject(Integer.parseInt(response));
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
SupportAdapter.java
public class supportAdapter extends ArrayAdapter<supportContent> {
private Context context;
private List<supportContent> contents;
public supportAdapter(Context context, List<supportContent> con){
super(context, R.layout.supportcontent, con);
this.contents = con;
}
#Override
public int getCount(){
return contents.size();
}
public View getView(int position, View convertview, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(getContext());
View supcon = inflater.inflate(R.layout.supportcontent, null);
TextView ticketnumber = (TextView)supcon.findViewById(R.id.ticketnumber);
ticketnumber.setText(contents.get(position).getTicketnumber());
TextView supportsubject = (TextView)supcon.findViewById(R.id.supportsubject);
supportsubject.setText(contents.get(position).getSubject());
TextView response = (TextView)supcon.findViewById(R.id.response);
response.setText(contents.get(position).getResponse());
return supcon;
}
}
Parse your response as below -
JSONObject jObj = new JSONObject(response);
JSONArray jResponseTicketarray = jObj.getJSONArray("responseticket");
JSONObject jTicket = jResponseTicketarray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
response - returned Json response in onResponse() mth.
jResponseTicketarray.getJSONObject(0); - here '0' is first element in ResponseTicketArray. If der are multiple object u might wanna iterate thr loop and extract required fields.
Modify below code too -
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
to below -
supportContent support = new supportContent();
support.setTicketnumber(TicketNumber);
support.setSubject(Subject);
support.setResponse(Response);
I am getting a NullPointerException at
image.setImageResource(R.drawable.cover);
Here's my code:
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
image.setImageResource(R.drawable.cover);
}
});
This code is running in a doInBackground() method. This is my ImageView in XML:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
NewsFeed.java
public class NewsFeed extends ListActivity {
MainActivity mainAct = new MainActivity();
private ProgressDialog pDialog;
// json url
// json tags
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_ID = "id";
private static String TAG_MESSAGE = "message";
private static final String TAG_CREATETIME = "created_time";
protected static final String JSONObject = null;
// contacts JSONArray
JSONArray contacts = null;
TimerTask timerTask;
Handler handler;
Timer ourtimer;
String url, gotToken, static_token, imgUrl, nextUrl = "none",
prevUrl = "none", paging;
ImageView image;
Bitmap myBitmap;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Bundle gotBasket = getIntent().getExtras();
// gotToken = gotBasket.getString("Access_Token");
static_token = "xxxxxxxxxxxxxxxx";
url = "https://graph.facebook.com/v2.2/awaaziitkgp/feed?access_token="
+ static_token;
setContentView(R.layout.news_feed);
image = (ImageView) findViewById(R.id.imageView1);
final TextView button1 = (TextView) findViewById(R.id.button1);
final TextView newPosts = (TextView) findViewById(R.id.nextPosts);
final TextView prevPosts = (TextView) findViewById(R.id.previousPosts);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Calling async task to get json
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_DATA);
JSONObject pagingObj = jsonObj.getJSONObject("paging");
// String nextObj = pagingObj.getString("next");
nextUrl = pagingObj.getString("next");
// JSONObject prevObj= pagingObj.getJSONObject("previous");
prevUrl = pagingObj.getString("previous");
Log.d("contact.length", String.valueOf(contacts.length()));
// looping through All Contacts
for (int i = 0; i < 25; i++) {
JSONObject c = contacts.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
String message = null;
String id = c.getString(TAG_ID);
data.put(TAG_ID, id);
if (c.has("description") == true) {
message = c.getString("description");
Log.d("Getting Description", message);
}
if (c.has("picture") == true) {
try {
Log.d("IT HAS PICTURE! TADA!!", "Image Found");
imgUrl = c.getString("picture");
Thread thread = new Thread(){
public void run(){
System.out.println("Thread Running");
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
URL newUrl = null;
try {
newUrl = new URL(imgUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myBitmap = getBitmapFromUrl(newUrl);
image.setImageBitmap(myBitmap);
}
});
}
};
thread.start();
} catch (Exception e) {
Log.d("ERROR LOADING IMAGE",
"Why you do this, InputStream? Why?");
}
}else{
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
((ImageView) findViewById(R.id.imageView1)).setImageResource(R.drawable.cover);
}
});
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
Here you can get a solution.
((ImageView)findViewById(R.id.image_view1)).setImageResource(R.drawable.cover);
XML Snippet:
<ImageView
android:id="#+id/image_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
You are trying to inflate a layout then use a view from another layout..
since you used R.layout.activity_main you can only use the views inside that layout nothing more..
but in your case you used the image1 = (ImageView) findViewById(R.id.dice1); which will reference a null value because it reside in your MAIN.xml not in activity_main.
So what you need to do is instead of using the activity_main layout use the appropriate layout which is setContentView(R.layout.MAIN);
Semi-new to programming Android apps, or apps in general. I'm trying to create a bunch of buttons based on JSON response. The response is coming back good (checked in Log.i) and no errors showing an issue, but the buttons aren't displaying. Here's my main activity, asynctask class and main xml. Any feedback super appreciated.
Main Activity:
public class MainActivity extends ActionBarActivity {
Spinner spinner;
public SpinAdapter adapter;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> barlist;
Brewery[] breweries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.planets_spinner);
Log.i("msg", "sent to json");
new DownloadJSON().execute();
Log.i("msg", "past to json");
}
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
barlist = new ArrayList<String>();
try
{
Log.i("msg", "inside try");
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://fltapmap.com/populate.php");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("breweries");
Log.i("msg", "breweries lengths: "+jsonarray.length());
breweries = new Brewery[jsonarray.length()];
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
breweries[i] = new Brewery();
breweries[i].setId(jsonobject.optInt("ID"));
breweries[i].setName(jsonobject.optString("brewery"));
}
}catch(Exception e)
{
Log.i("msg",""+e.getMessage());
}
return null;
}
protected void onPostExecute(Void args) {
// Spinner adapter
adapter = new SpinAdapter(MainActivity.this,android.R.layout.simple_spinner_item,breweries);
spinner.setAdapter(adapter);
// You can create an anonymous listener to handle the event when is selected an spinner item
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
// Here you get the current item (a User object) that is selected by its position
Brewery brewery = adapter.getItem(position);
// Here you can do the action you want to...
Log.i("msg", "inside selected method"+String.valueOf(brewery.getId()));
new RetrieveBeersTask(MainActivity.this, findViewById(R.id.beer_list)).execute(String.valueOf(brewery.getId()));
/*
jsonarray = jsonobject.getJSONArray("ontap");
Log.i("msg", "breweries lengths: "+jsonarray.length());
Button beer_btns[] = new Button[jsonarray.length()];
Log.i("msg","buttons made");
for (int i = 0; i < jsonarray.length(); i++) {
Log.i("msg","in loop"+String.valueOf(i));
LinearLayout layout = (LinearLayout)findViewById(R.id.beer_list);
beer_btns[i] = new Button(MainActivity.this);
beer_btns[i].setText(jsonarray.getJSONObject(i).getString("beer"));
beer_btns[i].setGravity(Gravity.CENTER_HORIZONTAL);
beer_btns[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add your code here
}
});
layout.addView(beer_btns[i]);
}
*/
}
#Override
public void onNothingSelected(AdapterView<?> adapter) { }
});
}
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AsyncTask Class
public class RetrieveBeersTask extends AsyncTask<String, Void, ArrayList<String>> {
private Exception exception;
JSONObject jsonobject;
public JSONArray jsonarray;
public ArrayList<String> return_beers;
private Activity myMain;
private View myLayout;
public RetrieveBeersTask(Activity passedin, View mainLayout) {
this.myMain = passedin;
this.myLayout = mainLayout;
}
#Override
protected ArrayList<String> doInBackground(String... brewery) {
try {
Log.i("msg", "inside launcher: Brewery - "+brewery[0]);
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://fltapmap.com/ontap.php?id="+brewery[0]);
HttpResponse response = httpclient.execute(request);
Log.i("msg","request back");
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
/*
Log.i("msg","ssending request");
HttpResponse response = httpclient.execute(request);
Log.i("msg","request back");
HttpEntity resEntity = response.getEntity();
Log.i("msg","should have response");
String _response=EntityUtils.toString(resEntity);
Log.i("msg","got repsonse"+_response);
*/
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("ontap");
return_beers = new ArrayList<String>();
for (int i = 0; i < jsonarray.length(); i++) {
Log.i("msg", "beer name: "+jsonarray.getJSONObject(i).getString("beer"));
return_beers.add(jsonarray.getJSONObject(i).getString("beer"));
}
return return_beers;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(ArrayList<String> beers) {
// TODO: check this.exception
// TODO: do something with the feed
Log.i("msg", "length of array: "+String.valueOf(beers.size()));
Button beer_btns[] = new Button[jsonarray.length()];
for (int i = 0; i < beers.size(); i++) {
beer_btns[i] = new Button(myMain);
beer_btns[i].setText(beers.get(i));
beer_btns[i].setGravity(Gravity.CENTER_HORIZONTAL);
beer_btns[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add your code here
}
});
LinearLayout layout = (LinearLayout)myLayout;
Log.i("msg",String.valueOf(layout));
layout.addView(beer_btns[i]);
}
}
}
I tried searching for similar questions but I cant find anything that fits in to what I am doing.. I'm trying to populate a listview from a database and whenever I run it, it doesn't display anything in the listview..
here is the logcat..
JSONException: Value {"message":"Patient Available","success":1,"post":[{"lname":"miradora doringo","address":"navotas, pilipinas","email":"tam.muqu23","age":"20","gender":"babae","remarks":"mabuting estudyante","patient_id":"6","contact":"361008762","fname":"jenelien"},{"lname":"andres","address":"manila","email":"julieannandres#gmail.com","age":"20","gender":"female","remarks":"trial","patient_id":"7","contact":"926644895","fname":"julie"}]} of type org.json.JSONObject cannot be converted to JSONArray
this is my Viewpatient.java:
public class Viewpatient extends ListActivity {
private Button create;
private ProgressDialog pDialog;
private static final String READ_PATIENT_URL = "http://192.168.43.15:8080/DoctorScheduler/activities/viewpatient.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POST = "post";
private static final String TAG_PATIENT = "patient_id";
private static final String TAG_FNAME = "fname";
private static final String TAG_LNAME = "lname";
private static final String TAG_AGE = "age";
private static final String TAG_GENDER = "gender";
private static final String TAG_CONTACT = "contact";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_REMARKS = "remarks";
JSONParser jsonParser = new JSONParser();
//array of all patient information by patient
JSONArray Apatient = null;
//manages all patient in a list
ArrayList<HashMap<String, String>> ApatientList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpatient);
ApatientList = new ArrayList<HashMap<String, String>>();
new LoadInformation().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// INSERT ALL PREVIOUS CONSULTATIONS OF THE PATIENT HERE
}
});
create = (Button) findViewById(R.id.BtnAdd);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent createInfo = new Intent(Viewpatient.this, Viewupdate.class);
startActivity(createInfo);
}
});
};
public class LoadInformation extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Viewpatient.this);
pDialog.setMessage("Loading all patient information....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Making a request to url and getting response
String json = jsonParser.getJSONFromURL(READ_PATIENT_URL, "POST", params);
Log.d("Response: ", "> " + json);
try {
Apatient = new JSONArray(json);
if (Apatient != null) {
// looping
for (int i = 0; i < Apatient.length(); i++) {
JSONObject c = Apatient.getJSONObject(i);
String patient_id = c.getString(TAG_PATIENT);
String fname = c.getString(TAG_FNAME);
String lname = c.getString(TAG_LNAME);
String age = c.getString(TAG_AGE);
String gender = c.getString(TAG_GENDER);
String contact = c.getString(TAG_CONTACT);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String remarks = c.getString(TAG_REMARKS);
// tmp hashmap for single contact
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT, patient_id);
map.put(TAG_FNAME, fname);
map.put(TAG_LNAME, lname);
map.put(TAG_AGE, age);
map.put(TAG_GENDER, gender);
map.put(TAG_CONTACT, contact);
map.put(TAG_EMAIL, email);
map.put(TAG_ADDRESS, address);
map.put(TAG_REMARKS, remarks);
// adding contact to contact list
ApatientList.add(map);
}
} else {
Log.e("Error", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
ListAdapter adapter = new SimpleAdapter(
Viewpatient.this, ApatientList, R.layout.main,
new String[] { TAG_PATIENT, TAG_FNAME, TAG_LNAME, TAG_AGE,
TAG_GENDER, TAG_CONTACT, TAG_EMAIL, TAG_ADDRESS, TAG_REMARKS },
new int[] { R.id.txtID, R.id.txtFName, R.id.txtLName, R.id.txtAge, R.id.txtGender,
R.id.txtContact, R.id.txtEmail, R.id.txtAddress, R.id.txtRemarks});
setListAdapter(adapter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewpatient, menu);
return true;
}
}
this my JSONParser.java:
public class JSONParser {
//new
static String response = null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
//constructor
public JSONParser(){
}
public String getJSONFromURL(String url, String method,
List<NameValuePair> params){
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == "GET") {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
and this is my viewpatient.php:
<?php
require ("../config.inc.php");
$query = "Select * From patientinfo";
try{
$stmt = $dbname->prepare($query);
$result = $stmt->execute();
}catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//retrieve all the rows
$rows = $stmt->fetchAll();
if($rows){
$response["success"] = 1;
$response["message"] = "Patient Available";
$response["post"] = array();
foreach($rows as $row){
$post = array();
$post["patient_id"] = $row["patient_id"];
$post["fname"] = $row["fname"];
$post["lname"] = $row["lname"];
$post["age"] = $row["age"];
$post["gender"] = $row["gender"];
$post["contact"] = $row["contact"];
$post["email"] = $row["email"];
$post["address"] = $row["address"];
$post["remarks"] = $row["remarks"];
//update json response
array_push($response["post"], $post);
}
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "No available patient information";
die(json_encode($response));
}
?>
You should change this part Apatient = new JSONArray(json);
Create a JSONObject JSONObject ApatientObject = new JSONObject(json);
Then get your JSONArray from there like this :
Apatient = new JSONArray(ApatientObject.getJSONArray("post"))
The problem is that the response you receive from the server is a JSONObject, not a JSONArray. The JSONObject contains 2 Strings, "message" and "success", and also contains a JSONArray "post" which holds the data you are looking for.
EDIT:
If you're only retreiving data from the server then it can be useful to think in terms of using GET for retrieving / viewing information and POST for creating / editing information as mentioned here:
When do you use POST and when do you use GET?