I have 3 textviews which I am attempting to update with data pulled via JSON - I'm not getting any errors with what I've built so far - but the textviews (nameTv, contentTv and publishedTv) don't seem to update with the data from my JSON query.
public class Player extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
String title = getIntent().getStringExtra("title");
String uploader = getIntent().getStringExtra("uploader");
String viewCount = getIntent().getStringExtra("viewCount");
TextView titleTv = (TextView) findViewById(R.id.titleTv);
TextView uploaderTv = (TextView) findViewById(R.id.uploaderTv);
TextView viewCountTv = (TextView) findViewById(R.id.viewCountTv);
titleTv.setText(title);
uploaderTv.setText("by" + uploader + " |");
viewCountTv.setText(viewCount + " views");
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(null, viewCount);
task.execute();
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(), "onInitializationFailure()",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
String video_id = getIntent().getStringExtra("id");
player.loadVideo(video_id);
}
}
public final class GetYouTubeUserCommentsTask extends
AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "CommentsLibrary";
private final Handler replyTo;
private final String username;
String video_id = getIntent().getStringExtra("id");
public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(
"http://gdata.youtube.com/feeds/api/videos/"
+ video_id
+ "/comments?v=2&alt=json&start-index=1&max-results=50&prettyprint=true");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response
.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(
"items");
List<Comments> comments = new ArrayList<Comments>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String content = jsonObject.getString("content");
String published = jsonObject.getString("published");
comments.add(new Comments(name, content, published));
TextView nameTv = (TextView) findViewById(R.id.name);
nameTv.setText(jsonObject.getString("name"));
TextView contentTv = (TextView) findViewById(R.id.content);
contentTv.setText(jsonObject.getString("content"));
TextView publishedTv = (TextView) findViewById(R.id.published);
publishedTv.setText(jsonObject.getString("published"));
}
CommentsLibrary lib = new CommentsLibrary(username, comments);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
You can not access the UI in doInBackground() -- please see the documentation. You will need to deliver the results to onPostExecute() and handle your UI updates there.
Related
I am trying to display main and description from json data i take from opneweathermap. And nothing happen, but I don't have errors.
I will not include the link.
Here is my MainActivity class
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mTextView = (TextView) findViewById(R.id.textView2);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask task = new DownloadTask();
task.execute("Link");
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char current = (char) data;
result+=current;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Toast.makeText(getApplicationContext(), "Soem"+message,Toast.LENGTH_LONG).show();
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i=0;i<array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message += main + ": " + description + "\r\n";
}
}
if(message != ""){
mTextView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I have included uses-permissions and i have TextView and Button that will display the data from json in my layout file.
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);
This is my code in a class that extends Asynctask and its doInBackground() method:
//Building Parameters
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, email));
//getting JSON string from url
JSONObject json = parser.makeHttpRequest(url_get_one_member, "POST",paramss);
Log.d("Ambil Member",json.toString());
//cari tag success
try{
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
member = json.getJSONArray(TAG_MEMBER);
JSONObject jObject = member.getJSONObject(0);
String emaill = jObject.getString(TAG_EMAIL);
String nama = jObject.getString(TAG_NAMA);
String alamat = jObject.getString(TAG_ALAMAT);
String no_telp = jObject.getString(TAG_NO_TELP);
String umur = jObject.getString(TAG_UMUR);
String tempatLahir = jObject.getString(TAG_TEMPAT_LAHIR);
String tglLahir = jObject.getString(TAG_TANGGAL_LAHIR);
String jlhPeliharaan = jObject.getString(TAG_JUMLAH_PELIHARAAN);
String warna = jObject.getString(TAG_WARNA_FAVORIT);
String jenisKelamin = jObject.getString(TAG_JENIS_KELAMIN);
String kota = jObject.getString(TAG_JENIS_KOTA);
//masukin semuanya ke variabel
txt_email.setText(emaill);
txt_nama.setText(nama);
txt_alamat.setText(alamat);
txt_no_telp.setText(no_telp);
txt_umur.setText(umur);
txt_tempat_lahir.setText(tempatLahir);
txt_tanggal_lahir.setText(tglLahir);
txt_jumlah_peliharaan.setText(jlhPeliharaan);
txt_warna_favorit.setText(warna);
if(jenisKelamin.equals("1")){
txt_jenis_kelamin.setText("Pria");
} else {
txt_jenis_kelamin.setText("Wanita");
}
txt_id_kota.setText(kota);
}
}catch (JSONException ex){
ex.printStackTrace();
}
return null;
Sometimes it works, sometimes it doesn't.
I've checked my logcat, the json.toString() is working but I can't set all the text to the TextView.
In onCreate() I've been initializing them all:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_profile);
//textview
txt_email = (TextView) findViewById(R.id.txt_email);
txt_nama = (TextView) findViewById(R.id.txt_nama);
txt_alamat = (TextView) findViewById(R.id.txt_alamat);
txt_no_telp = (TextView) findViewById(R.id.txt_no_telp);
txt_umur = (TextView) findViewById(R.id.txt_umur);
txt_tempat_lahir = (TextView) findViewById(R.id.txt_tempat_lahir);
txt_tanggal_lahir = (TextView) findViewById(R.id.txt_tanggal_lahir);
txt_jumlah_peliharaan = (TextView) findViewById(R.id.txt_jumlah_peliharaan);
txt_jenis_kelamin = (TextView) findViewById(R.id.txt_jenis_kelamin);
txt_warna_favorit = (TextView) findViewById(R.id.txt_warna_favorit);
txt_id_kota = (TextView) findViewById(R.id.txt_id_kota);
//button
buttonLogout = (Button) findViewById(R.id.buttonLogout);
buttonLogout.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
prefs = getSharedPreferences("login", Context.MODE_PRIVATE);
editor = prefs.edit();
editor.clear();
editor.commit();
Intent backToLogin = new Intent(Profile.this,Login.class);
startActivity(backToLogin);
finish();
}
});
btnEditProfil = (Button) findViewById(R.id.btnEditProfil);
btnEditProfil.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentEdit = new Intent(getApplicationContext(),EditProfile.class);
intentEdit.putExtra("emailMember", email);
startActivity(intentEdit);
}
});
btnPeliharaan = (Button) findViewById(R.id.btnPeliharaan);
btnPeliharaan.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentPeliharaan = new Intent(getApplicationContext(),ShowPeliharaan.class);
startActivity(intentPeliharaan);
}
});
//nagmbil email
Intent intent = getIntent();
email = intent.getStringExtra("emailMember");
new LoadMember().execute();
}
Write your AsyncTask class like this:
private class MyAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, email));
//getting JSON string from url
JSONObject json = parser.makeHttpRequest(url_get_one_member, "POST",paramss);
Log.d("Ambil Member",json.toString());
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json=new JSONObject(result);
try{
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
member = json.getJSONArray(TAG_MEMBER);
JSONObject jObject = member.getJSONObject(0);
String emaill = jObject.getString(TAG_EMAIL);
String nama = jObject.getString(TAG_NAMA);
String alamat = jObject.getString(TAG_ALAMAT);
String no_telp = jObject.getString(TAG_NO_TELP);
String umur = jObject.getString(TAG_UMUR);
String tempatLahir = jObject.getString(TAG_TEMPAT_LAHIR);
String tglLahir = jObject.getString(TAG_TANGGAL_LAHIR);
String jlhPeliharaan = jObject.getString(TAG_JUMLAH_PELIHARAAN);
String warna = jObject.getString(TAG_WARNA_FAVORIT);
String jenisKelamin = jObject.getString(TAG_JENIS_KELAMIN);
String kota = jObject.getString(TAG_JENIS_KOTA);
//masukin semuanya ke variabel
txt_email.setText(emaill);
txt_nama.setText(nama);
txt_alamat.setText(alamat);
txt_no_telp.setText(no_telp);
txt_umur.setText(umur);
txt_tempat_lahir.setText(tempatLahir);
txt_tanggal_lahir.setText(tglLahir);
txt_jumlah_peliharaan.setText(jlhPeliharaan);
txt_warna_favorit.setText(warna);
if(jenisKelamin.equals("1")){
txt_jenis_kelamin.setText("Pria");
} else {
txt_jenis_kelamin.setText("Wanita");
}
txt_id_kota.setText(kota);
}
}catch (JSONException ex){
ex.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
I am decoding jpeg images from a server request I get using json. I display them with a custom ListView Adapter along with a little text.
The images display correctly for the first 8 ImageViews in the ListView, however, after that it will no longer display the image (it will display the text). For example, if I have a total of 10 images, the last two images will not show in the ListView, but if I delete the first 2 images, the last two will show, so there is no concern about retrieving the actual images.
On my main activity (NotesActivity) I have a button that goes to another activity which does an asyntask, and in that async task in the onPostExecute, it returns back to the main activity where it should show the updated list (and it does, unless there are more than 8 images).
I don't know where to begin, any suggestions?
My Activity that contains the ListView
public class NotesActivity extends Activity implements OnClickListener {
String key = "NOTES";
String key2 = "UPDATE_NOTES";
Gson gson = new Gson();
// Notes myNotes = new Notes();
NotesList myNotes = new NotesList();
String bId;
String res = null;
EditText notes;
Button save;
private Button createNote;
private int position;
private String type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_layout);
createNote = (Button) findViewById(R.id.notes_layout_btn_createNote);
Bundle bundle = this.getIntent().getExtras();
position = bundle.getInt("position");
type = bundle.getString("type");
//
if (type.equals("LISTINGS")) {
Listings it = ListingsFragment.myListings.getListings().get(
position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
//
if (type.equals("SHARED")) {
Listings it = SharedFragment.myShared.getListings().get(position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
GetNotes getNotes = new GetNotes();
try {
NotesList copy = new NotesList();
getNotes.execute(key, bId).get();
for (int j = 0; j < myNotes.getNotes().size(); j++) {
Notes note = myNotes.getNotes().get(j);
System.out.println("Removed value: " + note.getIsRemoved());
if (note.getIsRemoved() == null) {
copy.getNotes().add(note);
}
}
NotesAdapter adapter = new NotesAdapter(this, R.layout.note_row,
copy.getNotes());
ListView lv = (ListView) findViewById(R.id.notes_layout_lv_notesList);
lv.setAdapter(adapter);
} catch (Exception e) {
}
createNote.setOnClickListener(this);
}
private class GetNotes extends AsyncTask<String, String, NotesList> {
#Override
protected NotesList doInBackground(String... things) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", things[0]));
postParameters.add(new BasicNameValuePair("bId", things[1]));
// String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
res = response.toString();
// System.out.println("This is the response " + res);
// res = res.trim();
// res= res.replaceAll("\\s+","");
// error.setText(res);
// System.out.println(res);
myNotes = gson.fromJson(res, NotesList.class);
// System.out.println(res);
} catch (Exception e) {
res = e.toString();
}
return myNotes;
}
#Override
protected void onPostExecute(NotesList res) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notes_layout_btn_createNote:
ProfileDataSource datasource = new ProfileDataSource(this);
datasource.open();
PropClipGlobal pcg = datasource.getUserIdenity();
Intent intent = new Intent(this, NewNoteActivity.class);
intent.putExtra("bId", bId);
intent.putExtra("uId", pcg.getUID());
intent.putExtra("username", pcg.getEm());
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
My custom adapter
public class NotesAdapter extends ArrayAdapter<Notes> {
List<Notes> notes;
Context context;
public NotesAdapter(Context context, int resource, List<Notes> notes) {
super(context, resource, notes);
this.notes = notes;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.note_row, null);
}
Notes note = notes.get(position);
ImageView icon = (ImageView) v.findViewById(R.id.note_row_icon);
TextView name = (TextView) v.findViewById(R.id.note_row_name);
TextView message = (TextView) v.findViewById(R.id.note_row_message);
TextView date = (TextView) v.findViewById(R.id.note_row_date);
String input = note.getNoteDate();
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputDf = new SimpleDateFormat("dd, yyyy");
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
Date myDate = null;
try {
myDate = inputDf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
String month = monthFormat.format(myDate);
date.setText(getMonth(Integer.parseInt(month)) + " "
+ outputDf.format(myDate));
message.setText(note.getNote());
name.setText(note.getFirstName() + " " + note.getLastName());
// System.out.println(p.getFileData());
byte[] imageAsBytes = Base64.decode(note.getFileData().getBytes(),
position);
icon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
System.out.println(note.getFileData());
return v;
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1];
}
}
Activity which eventually goes to the main activity (NotesActivity)
public class NewNoteActivity extends Activity implements OnClickListener {
private String uId;
private String bId;
private String username;
private String response;
private String key = "UPDATE_NOTES";
private Button submit;
private EditText note;
private int position;
private String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
submit = (Button) findViewById(R.id.activity_new_note_btn_submit);
note = (EditText) findViewById(R.id.activity_new_note_et_note);
Intent intent = getIntent();
bId = intent.getStringExtra("bId");
uId = intent.getStringExtra("uId");
username = intent.getStringExtra("username");
position = intent.getIntExtra("position", 0);
type = intent.getStringExtra("type");
submit.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
private class UpdateNotes extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... values) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", values[0]));
postParameters.add(new BasicNameValuePair("bId", values[1]));
postParameters.add(new BasicNameValuePair("uId", values[2]));
postParameters.add(new BasicNameValuePair("username", values[3]));
postParameters.add(new BasicNameValuePair("note", values[4]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
response = response.toString();
} catch (Exception e) {
response = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String response) {
Intent intent = new Intent(getApplicationContext(),
NotesActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
Toast toast = Toast.makeText(getApplicationContext(),"Added note!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
#Override
public void onClick(View v) {
String noteMessage = note.getText().toString();
UpdateNotes updateNotes = new UpdateNotes();
updateNotes.execute(key, bId, uId, username, noteMessage);
}
}
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);
}