Android Widget with asynctask - java

public class MainActivity extends AppWidgetProvider
{
TextView tv;
RemoteViews views;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context,appWidgetManager,appWidgetIds);
for(int i=0; i<appWidgetIds.length; i++){
int currentWidgetId = appWidgetIds[i];
views = new RemoteViews(context.getPackageName(),R.layout.activity_main);
appWidgetManager.updateAppWidget(currentWidgetId,views);
new PostTask().execute("url");
}
}
private class PostTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
// Dummy code
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(1, TimeUnit.MINUTES); // connect timeout
client.setReadTimeout(1, TimeUnit.MINUTES); // socket timeout
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "data=something");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "7a4d5df8-5aed-19bf-e1fb-c85f821c1d10")
.addHeader("content-type", "application/x-www-form-urlencoded")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e1) {
e1.printStackTrace();
return e1.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(result);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("response_data");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("CDRId").toString());
String name = jsonObject.optString("Status").toString();
data += "Agent : " + (i + 1) + "\nCDRId : " + id + " \n Status : " + name + " \n ";
}
views.setTextViewText(R.id.tv,data);
} catch (Exception e) {
views.setTextViewText(R.id.tv,e.toString());
}
}
}
}
I am trying to get a part of JSON(that I have parsed previously) in a widget. I am using AsyncTask to separate it from main thread and I am using OkHttpClient library to get JSON. I have class PostTask that gets me the parsed JSON. But can please anyone tell me how can I display it in the widget. This is the code.

Create a custom event, something like this:
public class MyEvent {
private String text;
public MyEvent(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text= text;
}
}
Now at the place where you're posting the Event, simply create this custom Event with the json you want to send to your widget. (put this code in onPostExecute).
EventBus.getDefault().post(new MyEvent(result);
Now simply wherever your textView is, in Activity or Fragment, register the eventBus in onCreate:
EventBus.getDefault().register(this);
And create a method that listens for the event like this:
#Subscribe
public void onMyEvent(MyEvent myEvent){
String text = myEvent.getText();
//Now you can parse this text, if it's JSON, or you can simply set it
//to your textView or whatever
}

Related

Update Data in Real Time when getting from server into RecylerView

I am getting json from Websockets and showing in recyler view. How do i update the list in real time when getting data from websockets?
My WebSocket Class
public final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
private static final String TAG = "DashBoardScreen.this";
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
initially when connection is established i send some text to server
webSocket.send(builder.toString());
}
#Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
in return server sends me data
output(text);
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
#Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
Log.d(TAG, "onClosing: ");
}
#Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
Log.d(TAG, "onClosed: ");
}
#Override
public void onFailure(WebSocket webSocket, Throwable t,Response response) {
super.onFailure(webSocket, t, response);
Log.d(TAG, "onFailure: ");
}
}
Output Method
private void output(final String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
*parsing json inside recyler view*
try {
JSONObject object = new JSONObject(text);
StringBuilder builder = new StringBuilder();
if (object.getBoolean("status")) {
JSONArray jsonArray = object.getJSONArray("events");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject values = jsonArray.getJSONObject(i);
final EventsDataModel dataModel = new EventsDataModel(
values.getString("service_Room_Number"),
values.getString("service_Name"),
values.getString("service_AssignedTo"),
values.getString("service_ID")
);
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
how exactly notifyDataSetChanged() works?
}
} else Toast.makeText(context, "No Events", Toast.LENGTH_SHORT).show();
System.out.println(builder.append(object.getString("status")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
Whenever your dataModel has the new data
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
If you perform the above operations and performing adapter.notifyDataSetChanged();
Will notify the adapter the new data has arrived and have to update the RecyclerView with new dataModel.

Getting Json exception for a string

I am calling an async task which returns a json object which has result,message as a string and result as cost.
Though it shows result,message string in the response object it shows json exception as no value for result.
Asynctask
public class SearchPostsAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
Context mContext;
private SearchPostsCallBack searchPostsCallBack;
private ProgressDialog loadingDialog;
private Snackbar snackbar;
private LinearLayout parentLayout;
private ArrayList<PostDelivery> list;
private JSONArray listsArray;
private JSONObject jsonObject;
public SearchPostsAsyncTask(Context context, LinearLayout linearLayout,SearchPostsCallBack searchPostsCallBack) {
this.mContext = context;
this.searchPostsCallBack = searchPostsCallBack;
this.parentLayout = linearLayout;
}
public interface SearchPostsCallBack {
void doPostExecute(ArrayList<PostDelivery> list);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = new ProgressDialog(mContext);
if (!isOnline()) {
snackbar = Snackbar.make(parentLayout, R.string.check_network, Snackbar.LENGTH_LONG);
snackbar.show();
} else {
loadingDialog.show(mContext, null,mContext.getString(R.string.wait));
}
}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = mContext.getResources().getString(R.string.url) + "requestlist";
jsonParams = new JSONObject();
jsonParams.put("st_lati", params[0]);
jsonParams.put("st_longi", params[1]);
jsonParams.put("ed_lati", params[2]);
jsonParams.put("ed_longi", params[3]);
jsonParams.put("pt_date", params[4]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendPostRequest(params[5]);
} catch (JSONException je) {
Log.e("exception",je.toString());
return Excpetion2JSON.getJSON(je);
} catch (Exception ue) {
return Excpetion2JSON.getJSON(ue);
}
}
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
if (loadingDialog.isShowing())
loadingDialog.dismiss();
try {
list = new ArrayList<>();
String result = response.getString("result");
String message = response.getString("message");
if (result.equals("1")) {
listsArray = response.getJSONArray("cost");
for (int j = 0; j < listsArray.length(); j++) {
jsonObject = listsArray.getJSONObject(j);
PostDelivery postDelivery = new PostDelivery();
postDelivery.setmPt_id(jsonObject.getString("pt_id"));
postDelivery.setmPt_name(jsonObject.getString("pt_name"));
postDelivery.setmPtDetail(jsonObject.getString("pt_detail"));
postDelivery.setmPtStartLoc(jsonObject.getString("pt_start_loc"));
postDelivery.setmPtEndLoc(jsonObject.getString("pt_end_loc"));
postDelivery.setmPtDate(jsonObject.getString("pt_date"));
list.add(postDelivery);
searchPostsCallBack.doPostExecute(list);
}
}
snackbar = Snackbar.make(parentLayout, "sorry", Snackbar.LENGTH_LONG);
snackbar.show();
}catch (JSONException je) {
je.printStackTrace();
// Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Exception and response :
D/ServerResponse: {"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
06-04 19:26:06.284 7129-7129/com.carryapp W/System.err: org.json.JSONException: No value for result
What is going wrong here? Please help.Thank you..
In your ServerResponse {"result":1}, the "result" is int, and you use String result = response.getString("result"), you should use getInt.
{"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung
mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
Form your attached response, it seems that the value of result is an int value and you are trying to get this value using:
String result = response.getString("result"); // WRONG
Try using:
int result = response.getInt("result");

How to set the arraylist to object after the postExecute of asyncTask?

I have 2 asyncTasks. One for GetCheckLists another for GetCheckListItems.
In CheckList class, it has checkListId,Title,etc and arrayList of checkListItems.
First I get all the checkLists using GetCheckListAsyncTask. Now for each checkList I am calling GetCheckListItemsAsync task to get all the checkListItems.
Now onPostExecute method of GetCheckListItemsAsyncTask I want to set the checkListItemArrayList.
How can I make sure to add checkListItemArrayList to checkList item's object?
CheckListActivity:
public class CheckListActivity extends AppCompatActivity implements CheckListAdapter.OnItemClickListener{
private ProgressDialog progressDialog;
private RecyclerView recyclerView;
private ArrayList<CheckList> checkLists = new ArrayList<>();
private CheckList mCheckList;
private ArrayList<CheckListItem> itemList;
private ArrayList<CheckList> checkListArrayList;
private CheckListAdapter mAdapter;
JSONArray checkListsItemArray,checkListArray;
public int iterationCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_list);
checkListArrayList = new ArrayList<>();
mEventId = mIntent.getStringExtra("eventId");
mCheckList = new CheckList();
progressDialog = new ProgressDialog(CheckListActivity.this);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
mAdapter = new CheckListAdapter(checkListArrayList,CheckListActivity.this,CheckListActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask();
getCheckListAsyncTask.execute(mEventId);
}
}
#Override
public class GetCheckListsItemAsyncTask extends AsyncTask<String, Void, JSONObject> {
private String api;
private JSONObject jsonParams;
public GetCheckListsItemAsyncTask(){}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = getResources().getString(R.string.server_url) + "api/checklist_items/getChecklistItems.php";
jsonParams = new JSONObject();
String checklistId = params[0]; // params[0] is username
jsonParams.put("checklistId", checklistId);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1) {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
checkListsItemArray = response.getJSONArray("checklistItems");
for (int i = 0; i < checkListsItemArray.length(); i++) {
int pendingTasks = 0,completedTasks = 0;
itemList = new ArrayList<>();
CheckListItem checkListItem = new CheckListItem();
JSONObject subObject = checkListsItemArray.getJSONObject(i);
String checkListItemName = subObject.getString("text");//name of the attribute in response
String checkListItemBudget = subObject.getString("budget");//name of the attribute in response
String checkListItemTimedate = subObject.getString("time_due");
String checkListItemReminder = subObject.getString("reminder");
String checkListItemId = subObject.getString("checklistItemId");
String checkListItemStatus = subObject.getString("status");
if (checkListItemStatus.equals("1")) {
completedTasks++;
}
if (checkListItemStatus.equals("0")) {
pendingTasks++;
}
checkListItem.setTitle(checkListItemName);
checkListItem.setBudget(checkListItemBudget);
checkListItem.setDateTime(checkListItemTimedate);
checkListItem.setReminder(checkListItemReminder);
checkListItem.setCheckListItemId(checkListItemId);
checkListItem.setStatus(checkListItemStatus);
checkListItem.setPendingItem(pendingTasks);
checkListItem.setCompletedItem(completedTasks);
itemList.add(checkListItem);//adding string to arraylist
}
if(checkListArrayList.size() < iterationCount) {
iterationCount++;
String checkListId =
checkListArrayList.get(iterationCount).getCheckListId();
CheckList checkList1 = checkListArrayList.get(iterationCount);
checkList1.setCheckListItemArrayList(itemList);
}
mAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
public class GetCheckListAsyncTask extends AsyncTask<String, Void, JSONObject> {
private String api;
private JSONObject jsonParams;
public GetCheckListAsyncTask(){}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = getResources().getString(R.string.server_url) + "api/checklist/getChecklists.php";
jsonParams = new JSONObject();
String eventId = params[0]; // params[0] is username
jsonParams.put("eventId", eventId);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
//Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
checkListArray = response.getJSONArray("checklists");
for (int i = 0; i < checkListArray.length(); i++) {
CheckList checkList = new CheckList();
JSONObject subObject = checkListArray.getJSONObject(i);
String checkListName = subObject.getString("checklist");//name of the attribute in response
String checkListBudget = subObject.getString("budget");//name of the attribute in response
String checkListIcon = subObject.getString("icon");
String checkListId = subObject.getString("checklistId");
checkList.setCheckListTitle(checkListName);
checkList.setBudget(checkListBudget);
checkList.setImageIcon(checkListIcon);
checkList.setCheckListId(checkListId);
checkListArrayList.add(checkList);
iterationCount++;
new GetCheckListsItemAsyncTask().execute(checkListId);
mAdapter.notifyDataSetChanged();
}
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
}
How to set CheckListItemsArrayList to the objects of checkListArrayList sequence wise? Please help. Thank you..
You need to elaborate your question. It is very confusing.
But I think that you want to add items to your AsyncTask class.
You can use the Constructor Method for this.
GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask(checkListsItemArray);
getCheckListAsyncTask.execute(mEventId);
And for AsyncTask Just Add:
JSONArray m_checkListsItemArray;
public GetCheckListsItemAsyncTask(JSONArray checkListsItemArray){
m_checkListsItemArray = checkListsItemArray;
//Do something here with checkListsItemArray;
}
And use m_checkListsItemArray anywhere in the AsycTask class.
Each time you start a task, you have no control when it ends. The tasks are running Asynchronously so they won't end in the order you start them. Maybe have a field level Array or ArrayList that adds results each time a task ends and then when everyhthing has ended you can work with the array results.

how to fetch data from url in mainactivity in android

the code i am using is working very fine for me but the problem is i am not able to fetch that data in main activity
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("firstname");
String lastname = c.getString("lastname");
String username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
this is the code new AsyncTaskParseJson().execute(); to make this thing work
but i need to run
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}`
I want to get the data like firstname , lastname , username as variable in main activity .
Is it possible ??
this is my other class IncomingCall.java when i want to get the variables
public class IncomingCall extends BroadcastReceiver {
private String firstname;
private String lastname;
private String username;
public void onReceive (Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, " Calling "+username, Toast.LENGTH_LONG).show();
try {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
notifyuser=true;
}
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(context, "Error detected 1 "+e, Toast.LENGTH_LONG).show();
}
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
// for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(0);
// Storing each json item in variable
firstname = c.getString("firstname");
lastname = c.getString("lastname");
username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
// }
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
protected void onPostExecute(String strFromDoInBg) {
Log.e("TAG1", "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
}
this is my code
The method onPostExecute runs on the main thread, You need to use the data once the doInBackground finishes and control return to the main thread.
Better you use these data in the method
protected void onPostExecute(String strFromDoInBg) {
// use the firstname , lastname or username after this method call.
}
Put your code in your Main Activity class, and then use class variables to store what you want, e.g.:
public class MainActivity extends Activity {
private String[] firstname;
private String[] lastname;
private String[] username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
firstname = new String[dataJsonArr.length()];
lastname = new String[dataJsonArr.length()];
username = new String[dataJsonArr.length()];
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
firstname[i] = c.getString("firstname");
lastname[i] = c.getString("lastname");
username[i] = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
Something like this (it's without error checking, give it a try)
EDIT: be sure to have declared the internet permission in the android manifest:
<uses-permission android:name="android.permission.INTERNET" />

Android - How to get specific data from URL/JSON?

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);
}

Categories

Resources