I can't seem to figure this out, since im just a beginner with this android stuff.
My app gets the customer names from my WebAPI via JSON.
Now I am trying to load it into a spinner, but how can I load my JSON arraylist in there?
I tried loading custTable in it but its shows "com.jetron.jetronbuitendienst.CustomerDetailsTable....." in the spinner now.
My Code:
package com.jetron.jetronbuitendienst;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Gegevens extends Main {
String Naam;
Spinner spCustomers;
private ArrayList<CustomerDetailsTable> Klanten;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gegevens);
new AsyncLoadCustDetails().execute();
spCustomers = (Spinner) findViewById(R.id.spKlanten);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
protected class AsyncLoadCustDetails extends
AsyncTask<Void, JSONObject, ArrayList<CustomerDetailsTable>> {
ArrayList<CustomerDetailsTable> custTable = null;
#Override
protected ArrayList<CustomerDetailsTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
Log.d("Customers: ", jsonObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadCustDetails", e.getMessage());
}
return custTable;
}
#Override
protected void onPostExecute(ArrayList<CustomerDetailsTable> result) {
// TODO Auto-generated method stub
// Application of the Array to the Spinner
ArrayAdapter<CustomerDetailsTable> spinnerArrayAdapter = new ArrayAdapter<CustomerDetailsTable>(getApplicationContext(), android.R.layout.simple_spinner_item, custTable);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spCustomers.setAdapter(spinnerArrayAdapter);
}
}
}
This is the jsonObj: D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}
Well Since you are getting this:
D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}
That implies that you are having an array that is called Value. So what you can do is this:
declare public variables :
private JSONObject jsonChildNode;
private JSONArray jsonMainNode;
private String name;
and then modify your code as:
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
Log.d("Customers: ", jsonObj.toString());
jsonMainNode = jsonObj.optJSONArray("Value");
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("Naam");
}
//and then you can add the name to a List<String> which will contain all the values of each item in the Value JSON Array.
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadCustDetails", e.getMessage());
}
Hope it helps!!!
That worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
Check API reference here.
ArrayAdapter uses the Object.toString() to fill the view.
Here in the code, with the Object CustomerDetailsTable does not override the toString() function, So it just print the name of the class.
Related
I got a problem when i want showing data with json from android with java
it showing nothing in here
But from json generator its fine
here is the example of json http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2
and here is my MainActivity.java
package com.example.callapi;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private static String url = "http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2";
ArrayList<HashMap<String,String>> bookList;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
bookList = new ArrayList<>();
}
private class getBooks extends AsyncTask<Void, Void,Void> {
#Override
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
ListAdapter listAdapter = new SimpleAdapter(MainActivity.this, bookList,R.layout.item,new String[]{"book_name"},new int[]{R.id.book_name});
listView.setAdapter(listAdapter);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading.....");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids){
Handler handler = new Handler();
String jsonString = handler.httpServiceCall(url);
if(jsonString!=null){
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray books = jsonObject.getJSONArray("Book");
for(int i= 0; i<books.length(); i++){
JSONObject jsonObject1 = books.getJSONObject(i);
String id_book = jsonObject1.getString("id_book");
String book_name = jsonObject1.getString("book_name");
HashMap<String,String> bookMap = new HashMap<>();
bookMap.put("id_book",id_book);
bookMap.put("book_name",book_name);
bookList.add(bookMap);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
}
});
}
}
else {
Toast.makeText(getApplicationContext(),"Server Error",Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}
}
and i saw something like this android.os.AsyncTask is deprecated
What's going on here? is something wrong with my code?
thanks
Yes, Async Task is deprecated now. There are already better and best alternate available those already handled these hacks of handling automatically and provide more readable and maintainable code. You must try one of those as I am mentioned below:
Retrofit
Volley
LoopJ
And many examples can be found over stack-overflow very easily.
First of all, we would need a full stack trace of your exception to check what is wrong with the code. At first, what I don't see is you ever executing AsyncTask. Even though AsyncTask is deprecated it still works but it's an old solution to modern problems.
To fix this I would probably suggest working with RxJava, here is an example of how:
private void process() {
try {
Observable.fromCallable(new Callable<JsonNode>() {
#Override
public JsonNode call() {
try {
JSONObject jsonObject;
//prepare your JSONObject for HttpClient
JsonParser jsonParser = new CustomHttpClient().postParser(url, jsonObject.toString());
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(jsonParser);
} catch (Exception e) {
e.getMessage();
}
return JsonNodeFactory.instance.objectNode();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<JsonNode>() {
#Override
public void accept(#NonNull JsonNode node) throws Exception {
try {
if (node == null || node.isEmpty()) {
return;
}
if (node.get("status_code").asInt() != 200) {
return;
}
//do something with your data
} catch (Exception e) {
e.getMessage();
}
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) {
Exception e = new Exception(throwable.getMessage());
}
}, new Action() {
#Override
public void run() throws Exception {
try {
} catch (Exception e) {
e.getMessage();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
To get the data you need just call the function like anyother
process();
In my case, I work with JsonNode and I use my CustomHttpClient which is a class for itself. But you can do whatever you want, just edit it accordingly. There are also many other implementations of this using other libraries but I found this easy to read, quick and understandable.
I've set up a php script to create json here, but when i try to display the JSONArray i got some error like this on my Android Monitor..
Value (html)(body)(script of type java.lang.String cannot be converted to JSONArray
can someone tell me how to fix it?
MainActivity.java
package flix.yudi.okhttp1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://zxccvvv.cuccfree.com/send_data.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan");
// looping through All Contacts
for (int i = 0; i < pertanyaan.length(); i++) {
JSONObject c = pertanyaan.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
// tmp hash map for single contact
HashMap<String, String> pertanyaans = new HashMap<>();
// adding each child node to HashMap key => value
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
// adding contact to contact list
contactList.add(pertanyaans);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
package flix.yudi.okhttp1;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I got the reference code from here
any idea/ another reference method to solve?
EDIT
send_data.php
<?php
include 'dbconfig.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, ask FROM pertanyaan";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row);
}
} else {
echo "0 results";
}
mysql_close($dbname);
echo $json;
?>
you are trying to get a jsonarray from jsonObj with key pertanyaan which in-fact is a string value so just traverse through array while fetching the json object using indexes
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan"); problem
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
HashMap<String, String> pertanyaans = new HashMap<>();
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
contactList.add(pertanyaans);
}
Note : There is no such jasonarray with key pertanyaan in your response
PHP update : Use
echo json_encode($json);
According to your service, while Response received you will get JSONArray like this [{"id":"1","ask":"pertanyaan ke 1"},{"id":"2","ask":"pertanyaan ke 2"},{"id":"3","ask":"pertanyaan ke 3"},{"id":"4","ask":"pertanyaan ke 4"},{"id":"5","ask":"pertanyaan ke 5"}]
you just need to store this response in JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray = (response);
now you have respons in your jsonArray so you can opt out value from it.
here is the sample code snippet
for (int i = 0; i < jsonArray.length(); i++) {
try {
String id = jsonArray.getJSONObject(i).getString("id");
String ask = jsonArray.getJSONObject(i).getString("ask");
Log.i("TAG", "id "+ id + " ask "+ ask);
//you can set value to text view here
textview.settext(id + " "+ ask);
} catch (JSONException e) {
e.printStackTrace();
}
}
I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have created Singleton class for SocketIOClient reference by here. Server was connected. I can able to send request from activity to SocketIOClient. But how can I get response from Singleton class in Activity?
Here My Activity:
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText uname, passwd;
Button login;
JSONObject json;
SocketIOClient socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
socket = new SocketIOClient();
try {
SocketIOClient.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json = new JSONObject();
uname = (EditText) findViewById(R.id.unameED);
passwd = (EditText) findViewById(R.id.passwdED);
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
json.put("username", uname.getText().toString().trim());
json.put("password", passwd.getText().toString().trim());
//request send to server
SocketIOClient.emit("login_request", json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Also My Singleton Class have on() method:
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
if (event.equals("registration_status")) {
jarr_args.put(args[0]);
try {
jobj_in = jarr_args.getJSONObject(0);
Log.d("Result", jobj_in.getString("result"));
if (jobj_in.getString("result").equals("success")) {
} else {
Log.d("check:", "username and password");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here Singleton class can get response from server. But I want to know,how to get the response in my activity?
Create an abstract class like this
public abstract class ResponseHandler
{
private Context context;
public abstract void execute (JSONObject jsonObject) throws JSONException;
public ResponseHandler (Context ctx)
{
this.context = ctx;
}
public void handleObject(JSONObject jsonObject) throws Exception
{
execute(jsonObject);
}
}
Inside your activity
While calling socket class, pass the ResponseHadler also as a parameter
Example:
SocketIOClient.initInstance(your parameters, new ResponseHandler(this)
{
//ResponseHandler have an abstract method called execute(). So you are overriding it here
#Override
public void execute(JSONObject jsonObject) throws JSONException
{
// Here you will get your JSONObject passed from socket class
}
}
And inside your socket class
public class YourSocketClass
{
private ResponseHandler handler;
public static void initInstance(your parameter, ResponseHandler responseHandler)
{
this.handler = responseHandler;
// Do your operations here
}
#Override
public void on(String event, IOAcknowledge ack, Object... args)
{
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
if (event.equals("registration_status"))
{
jarr_args.put(args[0]);
try
{
jobj_in = jarr_args.getJSONObject(0);
Log.d("Result", jobj_in.getString("result"));
if (jobj_in.getString("result").equals("success"))
{
//If you want to pass your jsonobject from here to activity
//Do something like this
handler.handleObject(jobj_in);
}
else
{
Log.d("check:", "username and password");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.
My code:
package com.berthojoris.bacaberita;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;
public class Berita extends ListActivity {
ProgressDialog dialog;
private static String urlBerita = "http://newapi.bacaberita.com/berita";
public ImageLoader imageLoader;
private JSONParser jParser;
Toast msg;
TextView notfound;
JSONArray contacts = null;
ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
BeritaAdapter adapter;
UtilBerita UtilBerita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
UtilBerita = new UtilBerita(this);
imageLoader = new ImageLoader(this.getApplicationContext());
notfound = (TextView) findViewById(R.id.notfound);
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
AmbilDataBean = new ArrayList<BeritaBean>();
adapter = new BeritaAdapter(this, AmbilDataBean);
setListAdapter(adapter);
Utils.setPolicyThread();
// Creating JSON Parser Instance
jParser = new JSONParser();
Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
+ UtilBerita.ReadBerita().size());
if (UtilBerita.ReadBerita().size() < 1) {
Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
new async().execute();
} else {
AmbilDataBean = UtilBerita.ReadBerita();
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity", "DATABASE DIAMBIL");
}
setTimerRefresh();
}// Tutup onCreate
private class async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AmbilDataBean = new ArrayList<BeritaBean>();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
return jsonContent;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.length() > 0) {
dialog.dismiss();
// parsing disini
JSONObject json = null;
try {
json = new JSONObject(result);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_ITEM);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(Constants.TAG_MenuID);
String judul = c.getString(Constants.TAG_Title);
//String img = c.getString(Constants.TAG_Link);
String desk = c.getString(Constants.TAG_Post);
String date = c.getString(Constants.TAG_Created);
BeritaBean mb = new BeritaBean();
mb.setID(id);
mb.setTitle(judul);
//mb.setLink("http://" + img);
mb.setPost(desk);
mb.setCreated(date);
AmbilDataBean.add(mb);
}
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity",
"PROSES SELESAI. DATA AKAN DITAMPILKAN");
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
} // Tutup if (result.length() > 0)
else {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Not Found. Please try again...",
Toast.LENGTH_SHORT).show();
}
if (AmbilDataBean.size() < 1) {
notfound.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
for (BeritaBean bean : AmbilDataBean) {
if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
Log.e("Berita Activity",
"Insert database : " + bean.getID());
UtilBerita.CreateData(bean);
} else {
Log.e("Berita Activity",
"Update database : " + bean.getID());
UtilBerita.UpdateBerita(bean);
}
}
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
} // Tutup onPostExecute
} // Tutup private class async extends AsyncTask
// =========================================================================================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
// =========================================================================================================================
// Declare the timer
Timer timer = null;
final Handler handler = new Handler();
public void setTimerRefresh() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.e("Main Activity", "RUNNING TASK...");
new async().execute();
}
});
}
}, 1000 * 60 * 1, 1000 * 25);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
if (UtilBerita != null)
UtilBerita.Close();
}
}
== UPDATE ==
My Constants class :
package com.berthojoris.bacaberita.lib;
public class Constants {
public static final String TAG_ITEM = "items";
public static final String TAG_MenuID = "Menu_ID";
public static final String TAG_IsDisplay = "IsDisplay";
public static final String TAG_CategoryName = "CategoryName";
public static final String TAG_CategoryID = "Category_ID";
public static final String TAG_ContentID = "Content_ID";
public static final String TAG_Title = "Title";
public static final String TAG_Post = "Post";
public static final String TAG_Link = "Link";
public static final String TAG_Meta = "Meta";
public static final String TAG_CreatedBy = "CreatedBy";
public static final String TAG_Created = "Created";
public static final String TAG_StartDisplay = "StartDisplay";
public static final String TAG_Counter = "counter";
}
You have to retrieve jsonArray from the jsonObject items. But in your code you have not used items anywhere. Try this way:
String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println("..........JSON OBJECT.............");
System.out.println(jsonObject); // full json Object
JSONArray jsonArray = jsonObject.getJSONArray("items");
System.out.println("..........JSON ARRAY PARSING.............");
for(int i=0;i<jsonArray.length();i++)
{
String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
System.out.println("MENU_ID: "+menu_id);
System.out.println("IsDisplay: "+is_display);
}
The methods used in above example are as follows:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}