Getting Json exception for a string - java

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

Related

How do I get current user's input data to show in listview?

I have an app where I use the info provided by the user to get a list of data
Using the code below, I'm getting two different results:
When where username = '$username' is presented on the PHP side, I receive just the Toast message. However, ListView remains empty.
When I remove where username = '$username' from PHP side, Toast message is displayed and the ListView also shows some content
Could you please help me to undestand why the ListView remains empty on that specific case?
Thanks in advance
Java
public void current_user() {
String url = "http://websie/my.php";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dayes = new SimpleDateFormat("dd-MM-yyyy");
final String created_date = dayes.format(calendar.getTime());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//System.out.println(response);
// Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
Toast.makeText(show_post_all_sales_2x100.this, response.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(show_post_all_sales_2x100.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", User.getUsername());
params.put("created_date", created_date);
return params;
}
};
RequestQueue requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpParseClass httpParseClass = new HttpParseClass(HttpURL);
try {
httpParseClass.ExecutePostRequest();
if (httpParseClass.getResponseCode() == 200) {
FinalJSonResult = httpParseClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subjects subjects;
SubjectList = new ArrayList<Subjects>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String tempName = jsonObject.getString("username").toString();
String tempFullForm = jsonObject.getString("created_date").toString();
subjects = new Subjects(tempName, tempFullForm);
SubjectList.add(subjects);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpParseClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$username = $_POST['username'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM post_2x where username = '$username'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Result when where username = '$username' is present
Result when I remove where username = '$username'

Detailed view on listview android

I have a listView that shows properties name, and it works well, but I have problems with showing detailed view of each announcement. When you are clicking on items that are in listView, I am getting empty activity_details, and the following error occurs in the debugger:
W/System.err: org.json.JSONException: Value No of type java.lang.String cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err: at com.example.said.populate.DetailsActivity$GetHttpResponse.doInBackground(DetailsActivity.java:205)
W/System.err: at com.example.said.populate.DetailsActivity$GetHttpResponse.doInBackground(DetailsActivity.java:180)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:831)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
This is PHP file that used for connection:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$StudentID= $_POST['propertyid'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM estate2 where id = '$propertyid'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Here is my DetailsActivity provided below:
public class DetailsActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "https://sultonkhuja1111.000webhostapp.com/MobApp/detail.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,PHONE_NUMBER,CLASS;
String NameHolder, NumberHolder, ClassHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
NAME = (TextView)findViewById(R.id.textName);
PHONE_NUMBER = (TextView)findViewById(R.id.textPhone);
CLASS = (TextView)findViewById(R.id.textClass);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(DetailsActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(DetailsActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("propertyid",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("property_name").toString() ;
NumberHolder = jsonObject.getString("price").toString() ;
ClassHolder = jsonObject.getString("description").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
PHONE_NUMBER.setText(NumberHolder);
CLASS.setText(ClassHolder);
}
}
}
And ShowingAllEstatesActivity:
public class ShowingAllEstatesActivity extends AppCompatActivity {
ListView SubjectListView;
ProgressBar progressBarSubject;
String ServerURL = "http://sultonkhuja1111.000webhostapp.com/MobApp/Estate.php";
List<String> IdList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showing_all_estates);
SubjectListView = (ListView)findViewById(R.id.listview1);
progressBarSubject = (ProgressBar)findViewById(R.id.progressBar);
new GetHttpResponse(ShowingAllEstatesActivity.this).execute();
//Adding ListView Item click Listener.
SubjectListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(ShowingAllEstatesActivity.this, DetailsActivity.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_listing, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.addNew:
startActivity(new Intent(this, AddPropertyActivity.class));
break;
}
return true;
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String ResultHolder;
List<subjects> subjectsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
subjectsList = new ArrayList<subjects>();
for(int i=0; i<jsonArray.length(); i++)
{
subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
IdList.add(jsonObject.getString("propertyid").toString());
subjects.SubjectName = jsonObject.getString("property_name");
subjectsList.add(subjects);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
if(subjectsList != null)
{
ListAdapter adapter = new ListAdapter(subjectsList, context);
SubjectListView.setAdapter(adapter);
}
}
}
}
This is code that is fetching for HttpUrl, detail.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$propertyid= $_POST['propertyid'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM estate2 where propertyid = '$propertyid'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
I think your HttpURL is not looking good. if this url not giving JSON response its will genrate same problem.

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.

JSON Query Does Not Update TextView

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.

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