I can't extract data from this json. I believe it is because it is an array. I read about it but I didn't find anything specific for this case.
I just need to take the values individually each time I close {}.
Eg: result [0] .getLoterias();
== INSTANTANEA
The connection is being made normally, I just can't extract the data.
httpservice2.java
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Gson().fromJson(resposta.toString(), CEP2.class);
}
}
Main3Activity.java:
package br.com.matheuscastiglioni.blog.requisicao_http;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
import br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2;
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
final TextView resposta = findViewById(R.id.etMain_resposta2);
final TextView cep = findViewById(R.id.etMain_resposta3);
final TextView token = findViewById(R.id.etMain_resposta4);
Bundle extras = getIntent().getExtras();
String respostatoken = extras.getString("token");
String respostaid = extras.getString("id");
cep.setText(respostaid);
token.setText(respostatoken);
//alert(cep.getText().toString() + token.getText().toString());
try {
CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get();
String loteria = retorno.getIdloteria();
resposta.setText(loteria);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private void alert(String s) {
Toast.makeText(this,s,Toast.LENGTH_LONG).show();
}
}
CEP2.java:
package br.com.matheuscastiglioni.blog.requisicao_http.model;
public class CEP2 {
private String idloteria;
public String getIdloteria() {
return idloteria;
}
public void setIdloteria(String idloteria) {
this.idloteria = idloteria;
}
}
currently:
I changed
return new Gson().fromJson(resposta.toString(), CEP2.class);
per
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
httpservic2 new:
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
}
}
I need to change the return from doinbackground However, I'm lost
It seems you only want the idloteria from the response which should be fine. But as you say it's an array and it should be parsed as an array or a List.
The:
return new Gson().fromJson(resposta.toString(), CEP2.class);
Should be
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
If you want the response be parsed as a list.
Another possibility is to get the data parsed as an array:
CEP2[] cep2Array = new Gson().fromJson(resposta.toString(), CEP2[].class);
return cep2Array;
and you'll need to change the return of the doInBackground in accordance with the response type you choose.
Lets choose to return a list. In this case change AsyncTask<Void, Void, CEP2> to AsyncTask<Void, Void, List<CEP2>> and also protected CEP2 doInBackground to protected List<CEP2> doInBackground.
The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List). And in this onPostExecute you can save the list, print it or do whatever you want to do with the received data.
But keep in mind that AsyncTask are deprecated in API level R. It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.
I want to parse an xml file of this form from a url into my android application.
<ArrayOfCurrency xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MobileAssignmentApi.Models">
<Currency>
<Buy>21.19573</Buy>
<CurrencyId>53</CurrencyId>
<Name>USD/MXN</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>21.15679</Sell>
</Currency>
<Currency>
<Buy>1.46806</Buy>
<CurrencyId>22</CurrencyId>
<Name>EUR/NZD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.46395</Sell>
</Currency>
<Currency>
<Buy>1.34658</Buy>
<CurrencyId>15</CurrencyId>
<Name>EUR/CAD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.3445</Sell>
</Currency>
.
.
.
</ArrayOfCurrency>
It is an array of currencies.
After a lot of effort i managed to parse the xml file into a string into my application.
The string have now the following form.
[{"currencyId":53,"buy":21.23042,"sell":21.1921,"name":"USD/MXN","pipMultiplier":10000},{"currencyId":22,"buy":1.50225,"sell":1.49891,"name":"EUR/NZD","pipMultiplier":10000},{"currencyId":15,"buy":1.38201,"sell":1.38083,"name":"EUR/CAD","pipMultiplier":10000},{"currencyId":62,"buy":0.69619,"sell":0.69404,"name":"NZD/CHF","pipMultiplier":10000},{"currencyId":19,"buy":80.085,"sell":79.968,"name":"NZD/JPY","pipMultiplier":100},{"currencyId":13,"buy":1.23727,"sell":1.23613,"name":"GBP/CHF","pipMultiplier":10000},{"currencyId":16,"buy":0.95424,"sell":0.95167,"name":"AUD/CAD","pipMultiplier":10000},{"currencyId":5,"buy":1.00469,"sell":1.00414,"name":"USD/CHF","pipMultiplier":10000},{"currencyId":1,"buy":122.014,"sell":121.839,"name":"EUR/JPY","pipMultiplier":100},{"currencyId":60,"buy":0.9092,"sell":0.90615,"name":"NZD/CAD","pipMultiplier":10000},{"currencyId":97,"buy":30.806,"sell":30.793,"name":"TRY/JPY","pipMultiplier":100},{"currencyId":10,"buy":0.68269,"sell":0.6823,"name":"NZD/USD","pipMultiplier":10000},{"currencyId":23,"buy":1.61316,"sell":1.61245,"name":"GBP/CAD","pipMultiplier":10000},{"currencyId":9,"buy":1.31115,"sell":1.31023,"name":"USD/CAD","pipMultiplier":10000},{"currencyId":3,"buy":1.21594,"sell":1.21552,"name":"GBP/USD","pipMultiplier":10000},{"currencyId":27,"buy":1.75536,"sell":1.7494,"name":"GBP/NZD","pipMultiplier":10000},{"currencyId":63,"buy":3.6378,"sell":3.62206,"name":"USD/TRY","pipMultiplier":10000},{"currencyId":64,"buy":3.83117,"sell":3.81819,"name":"EUR/TRY","pipMultiplier":10000},{"currencyId":28,"buy":0.73074,"sell":0.72814,"name":"AUD/CHF","pipMultiplier":10000},{"currencyId":50,"buy":9.54563,"sell":9.51557,"name":"EUR/SEK","pipMultiplier":10000},{"currencyId":18,"buy":87.091,"sell":86.919,"name":"CAD/JPY","pipMultiplier":100},{"currencyId":14,"buy":1.43031,"sell":1.4289,"name":"EUR/AUD","pipMultiplier":10000},{"currencyId":8,"buy":0.71693,"sell":0.7154,"name":"AUD/USD","pipMultiplier":10000},{"currencyId":17,"buy":83.97,"sell":83.811,"name":"AUD/JPY","pipMultiplier":100},{"currencyId":11,"buy":0.84385,"sell":0.84329,"name":"EUR/GBP","pipMultiplier":10000},{"currencyId":4,"buy":115.641,"sell":115.555,"name":"USD/JPY","pipMultiplier":100},{"currencyId":61,"buy":0.75641,"sell":0.75508,"name":"CAD/CHF","pipMultiplier":10000},{"currencyId":20,"buy":1.67121,"sell":1.66758,"name":"GBP/AUD","pipMultiplier":10000},{"currencyId":76,"buy":1171.7,"sell":1170.674,"name":"XAU/USD","pipMultiplier":100},{"currencyId":6,"buy":142.45,"sell":142.188,"name":"GBP/JPY","pipMultiplier":100},{"currencyId":2,"buy":1.04081,"sell":1.03929,"name":"EUR/USD","pipMultiplier":10000},{"currencyId":54,"buy":13.77633,"sell":13.70746,"name":"USD/ZAR","pipMultiplier":10000},{"currencyId":7,"buy":1.05845,"sell":1.05868,"name":"EUR/CHF","pipMultiplier":10000},{"currencyId":52,"buy":8.53823,"sell":8.51386,"name":"USD/NOK","pipMultiplier":10000},{"currencyId":48,"buy":9.0615,"sell":9.03791,"name":"USD/SEK","pipMultiplier":10000},{"currencyId":12,"buy":113.73,"sell":113.454,"name":"CHF/JPY","pipMultiplier":100},{"currencyId":21,"buy":1.03599,"sell":1.03438,"name":"AUD/NZD","pipMultiplier":10000},{"currencyId":51,"buy":8.99332,"sell":8.96375,"name":"EUR/NOK","pipMultiplier":10000},{"currencyId":150,"buy":6.7165,"sell":6.7144,"name":"USD/CNH","pipMultiplier":1000},{"currencyId":77,"buy":15.142,"sell":15.112,"name":"XAG/USD","pipMultiplier":100},{"currencyId":93,"buy":7.182,"sell":7.129,"name":"ZAR/JPY","pipMultiplier":100}]
using the following code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
String str = "http://massignment.zulutrade.com/api/rates";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskClass().execute(str);
}
class AsyncTaskClass extends AsyncTask<String, Void,String > {
private Exception exception;
protected String doInBackground(String ...params) {
URLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(str);
connection = url.openConnection();
connection.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
StringBuilder builder = new StringBuilder();
int i=0;
while ((line = reader.readLine()) != null) {
builder.append(line+"\n");
// Log.w("Response ", "> " + line );
i++;
}
String xml = builder.toString();
}
catch( IOException e) {
e.printStackTrace();
}
return "0k";
}
protected void onPostExecute() {
}
}
}
I need to parse that xml/string to its contents.
Any idea how can i do that parsing?
Assuming that your code is in Java - there are some good XML parsers available. You may want to use one of them to parse your XML.
I am trying to parse JSON, I have done it there before but not quiet this way. I spent hours trying to solve the problem, but I dont know what is wrong with the code.I am attaching the entire code for the activity, Web Request class and the layout. Any help will be greatly appreciated.
I get this error
java.io.FileNotFoundException: /data/system/users/sdp_engine_list.xml: open failed: ENOENT (No such file or directory)
05-19 18:17:27.427 3450-3450/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
05-19 18:17:28.232 3450-3592/? W/DisplayManagerService: Failed to notify process 20004 that displays changed, assuming it died.
This is the activity Transactions class.
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.rectuca.iyzicodemo.Classes.Transaction;
import com.rectuca.iyzicodemo.Library.WebRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Transactions extends ListActivity {
// URL to get contacts JSON
private static String url = "http://www.mocky.io/v2/573dbd243700005f194dcdcc";
// JSON Node names
private static final String TAG_PAYMENTS= "payments";
private static final String TAG_PAYMENT_ID = "paymentId";
private static final String TAG_SENT_BY = "sentBy";
private static final String TAG_DATE_TIME = "dateTime";
private static final String TAG_SENT_TO = "sentTo";
private static final String TAG_BANK_NAME = "bankName";
private static final String TAG_INSTALLMENTS = "installments";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_3DS = "threeDs";
private static final String TAG_CANCELLED = "cancelled";
private static final String TAG_RETURNED = "returned";
private static final String TAG_TRANSACTION_STATUS = "transactionStatus";
private static final String TAG_BLOCKAGE_AMOUNT = "blockage_amount";
private static final String TAG_BLOCKAGE_RELEASE_DATE = "blockageReleaseDate";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
// Calling async task to get json
new GetInfo().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetInfo extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> transactionInfoList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(Transactions.this);
proDialog.setMessage("Please Wait...");
proDialog.setCancelable(false);
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webReq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webReq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
transactionInfoList = ParseJSON(jsonStr);
return null;
}
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
transactionInfoList=new ArrayList<HashMap<String, String>>();
ListAdapter adapter = new SimpleAdapter(
Transactions.this, transactionInfoList,
R.layout.row_layout, new String[]{TAG_SENT_TO,TAG_DATE_TIME
,TAG_BANK_NAME,TAG_AMOUNT,TAG_3DS, TAG_CANCELLED,
TAG_RETURNED},
new int[]{R.id.name,R.id.dateTime ,R.id.bankName,R.id.amount,
R.id.threeDS, R.id.cancelled, R.id.returned});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> paymentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray payments = jsonObj.getJSONArray(TAG_PAYMENTS);
// looping through All Payments
for (int i = 0; i < payments.length(); i++) {
JSONObject c = payments.getJSONObject(i);
String dateTime =c.getString(TAG_DATE_TIME);
String sentTo =c.getString(TAG_SENT_TO);
String bankName =c.getString(TAG_BANK_NAME)+" ( "+c.getString(TAG_INSTALLMENTS)+" ) " ;
String amount =c.getString(TAG_AMOUNT);
String threeDS =c.getString(TAG_3DS);
String cancelled =c.getString(TAG_CANCELLED);
String returned =c.getString(TAG_RETURNED);
// temporary hashmap for a single payment
HashMap<String, String> payment = new HashMap<String, String>();
// adding every child node to HashMap key => value
payment.put(TAG_DATE_TIME, dateTime);
payment.put(TAG_SENT_TO, sentTo);
payment.put(TAG_BANK_NAME, bankName);
payment.put(TAG_AMOUNT, amount);
payment.put(TAG_3DS, threeDS);
payment.put(TAG_CANCELLED, cancelled);
payment.put(TAG_RETURNED, returned);
// adding student to students list
paymentList.add(payment);
}
return paymentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
This is the WebRequest Class
package com.rectuca.iyzicodemo.Library;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class WebRequest {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* #url - url to make request
* #requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* #url - url to make request
* #requestmethod - http request method
* #params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
This is what I am trying to do
http://lh3.googleusercontent.com/JqcySZU2Pz067NutlDvPP5Zq_3n_WSAllIuEdjQjOjyeGkKguaMNCrltaKbjBCi16g=h900-rw
I would suggest you to use
VOLLEY networking library by google
You should try to use Volley JSONOBJECTREQUEST() and you won't have any issue after that parsing will be easier.
add this to dependency section of your app
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Giving the error In EXCEPTION .... json data parsing error in catch in postexecute metod please help how to resolve.when the data entered in it it and it start working smothly but when time to send data it show that json data parsing error
/**
* Created by Mian on 2/28/2016.
*/
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
String userName = arg0[1];
String passWord = arg0[2];
String phoneNumber = arg0[3];
String emailAddress = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://livethuglife.com/signup.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result.toString();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfull.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Better to use a Class as per your Form that you have been Posting to the Server.
A Simple Java class with the number of field which needs to carry complete data of form to the server. Like i have defined as SignUp Class.
Then make a object of that Class SignUp Filled the object to corresponding values that you want to post to the server.
Now Change that object to JSON Using Google gson.jar (You may download it by searching it on the internet)
A Simple Example I have shown to you..
A Simple POJO Class SignUP
Class SignUP{
private String fullname;
private String username;
private String passoword; // Define Number of Variable as per your Need
private String phonenumber;
private String emailaddress;
//Getter and Setters Method.
}
Now Instantiate your class and try Google GSON library jars to parse it as JSON Object.
A Simple Logic to Convert Object of Class SignUP to JSON .
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
String userName = arg0[1];
String passWord = arg0[2];
String phoneNumber = arg0[3];
String emailAddress = arg0[4];
SignUP obj = new SignUP();
obj.setFullName(URLEncoder.encode(fullName, "UTF-8"));
obj.setUserName(URLEncoder.encode(userName, "UTF-8"));
obj.setPassword(URLEncoder.encode(passWord, "UTF-8"););
obj.setPhoneNumber(URLEncoder.encode(phoneNumber,"UTF-8"););
obj.setEmailAddress(URLEncoder.encode(emailAddress, "UTF-8"););
Gson gson = new Gson();
System.out.println(gson.toJson(obj));
}
Output:
{
"fullName":"FullName",
"username":"Lokesh",
"password":"Gupta",
"phonenumber":"73479273423",
"emailaddress":"abc #abc.com"
}
You may also try How to Convert Java Object to JSON Using Google GSON API
I've intentionally copy-pasted this question dont be angry for duplicate.
There are several unclear moments for me in the topic:
1)
xmpp.login(apiKey + "|" + sessionKey, sessionSecret, "Application");
sessionKey is the second part of the access token. If the token is in
this form, AAA|BBB|CCC, the BBB is the session key
But my access token looks like: BAADcfjCWMLABAIyzRSZA69eAtA9Dr3EQVlXA8Ql6rr5odDWxNYZCHhssiaar8S0gaPLZAm1ZBKCqWO3QFegJPR39hT0JR5ZCyIP1AJZC19qh9mFAExUd9KDjJ05yjE3IUZD
so I cant see any "second part"...
2)
sessionSecret is obtained using the old REST API with the method
auth.promoteSession. To use it, it's needed to make a Http get to this
url:
https://api.facebook.com/method/auth.promoteSession?access_token=yourAccessToken
Despite of the Facebook Chat documentation says that it's needed to
use your application secret key, only when I used the key that
returned that REST method I was able to make it works. To make that
method works, you have to disable the Disable Deprecated Auth Methods
option in the Advance tab in your application settings.
I've read here that REST is deprecated and
We will not be supporting this method in the Graph API.
What should I do? I'm using only Graph API. Is there any other way to get sessionSecret?
Thanks!
I tested this one and it worked for me .
First of all Edit your SASLXFacebookPlatformMechanism class . Copy and paste this code .
package com.facebook.android;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
import org.apache.harmony.javax.security.sasl.Sasl;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.sasl.SASLMechanism;
import org.jivesoftware.smack.util.Base64;
import android.util.Log;
public class SASLXFacebookPlatformMechanism extends SASLMechanism {
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String accessToken = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication) {
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException {
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKey, String host, String accessToken) throws IOException, XMPPException {
if (apiKey == null || accessToken == null) {
throw new IllegalArgumentException("Invalid parameters");
}
this.apiKey = apiKey;
this.accessToken = accessToken;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh) throws IOException, XMPPException {
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh);
authenticate();
}
#Override
protected String getName() {
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException {
byte[] response = null;
if (challenge != null) {
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
String composedResponse =
"method=" + URLEncoder.encode(method, "utf-8") +
"&nonce=" + URLEncoder.encode(nonce, "utf-8") +
"&access_token=" + URLEncoder.encode(accessToken, "utf-8") +
"&api_key=" + URLEncoder.encode(apiKey, "utf-8") +
"&call_id=0" +
"&v=" + URLEncoder.encode(version, "utf-8");
response = composedResponse.getBytes();
}
String authenticationText = "";
if (response != null) {
authenticationText = Base64.encodeBytes(response);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query) {
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params) {
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
}
Then use this method in your activity class from where you want to login to facebook.
private void testLogin(){
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
Log.i("XMPPClient",
"Access token to " + mFacebook.getAccessToken());
Log.i("XMPPClient",
"Access token to " + mFacebook.getAppId());
Log.i("XMPPClient",
"Access token to " + mFacebook.getAccessToken());
try {
xmpp.connect();
Log.i("XMPPClient",
"Connected to " + xmpp.getHost());
} catch (XMPPException e1) {
Log.i("XMPPClient",
"Unable to " + xmpp.getHost());
e1.printStackTrace();
}
try {
xmpp.login(PreferenceConnector.APP_ID, mFacebook.getAccessToken());
getRoster(xmpp);
} catch (XMPPException e) {
e.printStackTrace();
}
}