I'm currently studying this tutorial http://www.android-examples.com/android-json-parsing-retrieve-from-url-and-set-mysql-db-data/
It runs perfectly but now I would like to display all of the JSON values in the text view. I am new to JSON and only has a bit of experience in android.
Here is my MainActivity.java. I modified it a bit from the tutorial
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
}
and this is my JSON. It is a lot different from the tutorial
[{"id":"1","name":"white","status":"0"},{"id":"2","name":"red","status":"10"},{"id":"5","name":"blue","status":"15"}]
So obviously my code only displays the first name "white". I can't understand how to iterate the JSONObject to display all the values. I tried the answers in other questions but I can't quite incorporate them in my code.
That's because you're just getting the first element from JSONArray. (Index 0)
You should iterate over JSONArray to get all the JSONObject within an array.
Like this,
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i); // Replace 0 with i'th index.
// use this json object to iterate over individual objects.
}
Here's example of json parsing and insert , update , delete or get data from server with source you should try this !
Happy Coding!
The problem of your code is what Alok Patel stated. But I see that the logic of your code needs some changes to do what you want (according to sample json that you posted). You called parse method on values which are in fact simple data while you should call it on jsonObjects.
I refactored your code as below to do what you want:
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
Map<String,String> out = new Map<String, String>();
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i);
parse(json, out);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
// print "out" object to console here by iterating over its keys
// or do any needed process on it here.
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
val = json.getString(key);
}catch(Exception e){
}
if(val != null){
out.put(key,val);
}
}
return out;
}
}
Related
I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));
I have to hit a service and if the response came true than I have to verify the user & save the user entered variables in shared preference. my url is: http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id and the response it is giving is {"success":true}. For this I have made a class and declared a static method. Inside the static method I have to do parsing.
my class:
public class InitializeSDK {
/*String json = "";
URL url;
HttpURLConnection connection = null;*/
public static void init(final Context ctx, int offerwall_id, String offerwall_public_key) {
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... arg0) {
//TODO: add code to read http request and store the json data in json variable
String json = "";
//URL url;
HttpURLConnection connection = null;
InputStream is = null;
final String MyPREFERENCES = "MyPrefs" ;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id");//YOUR URL
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONObject jObj = new JSONObject(json);
boolean isSuccess = jObj.getBoolean("success");
System.out.println("success : " + isSuccess);
// SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
/*SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Context ctx);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isSuccess",isSuccess);
editor.commit();*/
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/* JSONObject jsonObject = new JSONObject(json);
boolean state = jsonObject.getBoolean("success");*/
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}.execute();
}
my MainActivity is:
public class MainActivity extends AppCompatActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
}
How to save the variables in sharedpreference and connect the class with MainActivity? Please help
Do the below changes.
Step1: Change Return type Void to Boolean
new AsyncTask<Void, Void, Boolean>() {}
Step2: In doInBackground return "isSuccess"
Step3: Change the onPostExecute() below
protected void onPostExecute(boolean result) {
super.onPostExecute(result);
if(result){
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putInt"offerwall_id", offerwall_id)
.putString("offerwall_public_key",offerwall_public_key)
.apply();
}
}
Step4: Call from MainActivity
public class MainActivity extends AppCompatActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitializeSDK.init(this,val1,val2);
}
}
}
Make InitializeSDK class extend AsyncTask
like
public class InitializeSDK extends AsyncTask<Void, Integer, String> {
Context ctx;
int offerwall_id;
String offerwall_public_key;
public InitializeSDK (Context ctx, int offerwall_id, String offerwall_public_key){
this.ctx = ctx;
this.offerwall_id = offerwall_id;
this.offerwall_public_key = offerwall_public_key;
}
//rest of the asynctask code
}
and in your MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int id = //your id;
String offerwall_public_key = //your key;
new IntializeSDK(this,id,offerwall_public_key).execute();
}
Your shared preference code is correct, use it in OnPostExecute
Sooo here is my OnCreateView code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
tvMemberName = (TextView) v.findViewById(R.id.member_name);
UrlPostHelper uph = new UrlPostHelper();
uph.execute();
return v;
}
and AsyncTask
private class UrlPostHelper extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String url = "http://localhost:8080/MP/Profile";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
String data = "no response";
try {
response = httpClient.execute(httpGet);
data = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "yow";
try {
JSONArray ja = new JSONArray(data);
for (int i = 0 ; i < ja.length(); i++ ){
JSONObject j = ja.getJSONObject(i);
String firstName = j.getString("firstName");
String lastName = j.getString("lastName");
System.out.println(firstName);
s = firstName +" " + lastName;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.i("TAG", result );
tvMemberName.setText(result);
}
}
My problem is that in my android app it does not show anything at first but after a while like around 1-2 minutes the "yow" will show. It is not replaced with the member name though. I tried running my servlet and it works just fine. Please help me.
AsyncTask<Params, Progress, Result>.
private class UrlPostHelper extends AsyncTask<Void, Void, String>{
private EditText tvMemberName;
public UrlPostHelper(EditText tv){
this.tvMemberName = tv;
}
Return Text after background task finished.
#Override
protected String doInBackground(Void... params) {
HttpResponse response;
String data = "no response";
try {
response = httpClient.execute(httpGet);
data = getJSONString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return data; //Text to set TvMember Value
}
Get String from response Util.
public String getJSONString(InputStream is) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
Set EditText onPostExecute.
protected void onPostExecute(String result){
Log.i("TAG", result );
tvMemberName.setText(result);
}
Pass EditText with the UrlPostHelper call.
new UrlPostHelper(tvMemberName).excute();
I'm using Android SDK 4.0 API14 and I want to run multiple AsyncTask in one class, I want the called async task to wait while the one before it is finished, but is seems I can't accomplish this, even if I test the status of the one currently being executed. this is my code :
if(isNetworkAvailable()){
new SpinnerTask().execute();
new RiderTask().execute();
new BankTask().execute();
}
//spinner bank
public class BankTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_bank.htm?type=pusat";
public BankTask(){
this.url=url;
System.out.println(url);}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
// Response(result.replace("\n", "").trim());
System.out.println("done for Bank");
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("BANK PUSAT");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
String LSBP_NAMA = spinner.optString("LSBP_NAMA");
int LSBP_ID = spinner.optInt("LSBP_ID");
helper.InsertBank(LSBP_ID, LSBP_NAMA);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
}
}catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//spinner bank
public class CabBankTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_bank.htm?type=cabang";
public CabBankTask(){
this.url=url;
System.out.println(url);}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
// Response(result.replace("\n", "").trim());
System.out.println("done for Cabang");
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("BANK CABANG");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
int LSBP_ID = spinner.optInt("LSBP_ID");
int LBN_ID = spinner.optInt("LBN_ID");
String LBN_NAMA = spinner.optString("LBN_NAMA");
helper.InsertCabBank(LSBP_ID, LBN_ID, LBN_NAMA);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
}
}catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//spinner produk
public class SpinnerTask extends AsyncTask<Void, Void, String>{
// String url="http://epolicy.sinarmasmsiglife.co.id/ios/spaj_prod.htm?model=1";
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_prod.htm?type=bancass";
public SpinnerTask(){
this.url=url;
System.out.println(url);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
// dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Produk..");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// dialog.dismiss();
super.onPostExecute(result);
fetchResponse(result.replace("\n", "").trim());
System.out.println("done for product");
}
}
private void fetchResponse(String result) {
if (!result.equals("")) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("PRODUK");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
String LSBS_ID = spinner.optString("LSBS_ID");
String LSBS_NAME = spinner.optString("LSBS_NAME");
helper.InsertSpin_Produk(LSBS_ID, LSBS_NAME);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
JSONArray PRODUK1 = spinner.getJSONArray("SUB_PRODUK");
for (int j=0; j<PRODUK1.length();j++){
JSONObject sub = PRODUK1.getJSONObject(j);
String LSDBS_NUMBER = sub.optString("LSDBS_NUMBER");
String LSDBS_NAME = sub.optString("LSDBS_NAME");
helper.InsertSpin_SubProduk(LSBS_ID,LSBS_NAME,LSDBS_NUMBER, LSDBS_NAME);
System.out.println("tes VarSpinner 1\2");
}
}
}
catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//Rider
public class RiderTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_prod.htm?type=rider";
public RiderTask(){
this.url=url;
System.out.println(url);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
Response(result.replace("\n", "").trim());
System.out.println("done for ridern");
}
}
is there any way to run multiple Asynctask in one class? thank u very much
Have a look on the AsyncTask.executeOnExecutor() method. It will run AsyncTasks in parallel. But make sure that the Tasks you run are independent from each other. As mentioned in the docs there is no given order in which the Tasks will be executed.
Call your Tasks like this:
new SpinnerTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
What you can do is, you can call second AsyncTask on onPostExecute() of first AsyncTask and so on.
e.g
public class FirstAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// your code
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// new SecondAsyncTask().execute();
}}
I am creating an Online Dictionary Android App.
I am using JSON to request for definitions for a word which the user inputs.
This input is into the variable "text" everytime the search button is clicked.
The Inputted word is then appended into the API request URL which returns the definition......which is stored in variable "result" in the bottom method OnPost Execute()
My TextView should then be set to this String.
I Therefore put the entire JSON and HTTPrequest code within the onClickLIstener because the user input always changes and requests everytime, but im getting an error at the "throws ClientProtocolException" after the "public JSONObject lastTweet(String word)" the error is "Syntax error on tokens, delete these tokens" I am Using Enclipse Indigo.
Here Is my Code:
public class Dictionary extends Activity {
String finalresult;
HttpClient client = new DefaultHttpClient();
TextView ansa;
JSONObject json;
Button Search;
EditText input;
String text;
final static String URL = "http://api.wordnik.com/v4/word.json/";
final static String URL2 = "/definitions?api_key=<MY API KEY>";
String fresult;
Dictionary dic = new Dictionary();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
ansa = (TextView) findViewById(R.id.ansa);
input = (EditText) findViewById(R.id.input);
Search = (Button) findViewById(R.id.search);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
text = input.getText().toString();
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
ansa.setText(fresult);
}
});
}
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
}
Any Suggestions?
Have you tried moving the request code to another class?