json data parsing error android studio [closed] - java

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

Related

Json data fetching lag problem from jsonbin.io

I'm working on a app that is a simple game, so here's a picture for the UI I have, the problem is when I fetch a level using Json web service, the first time I choose the level from activity_level_list, the picture and level number doesn't show, only the 4 words works but neither the image nor the level number appear like this.
NOTE: The image URL variable is null (because of the lag that happens the first time I open first level activity) so an error happen (that's why it shows ic_launcher instead of showing the level picture).
So, I said the problem was "lag" because when I go back to LevelList and click on level 1, the picture and the level number get fetched and everything becomes good.
How can I make it both the image and level ID appears in the first time I open the activity?
NOTE: I use jsonbin.io for data fetching.
Here's my Json data fetching class:
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
public class FetchData extends AsyncTask<Void,Void,Void> {
String update = "4";
String data ="";
String id;
String img;
String w1;
String w2;
String w3;
String w4;
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
// for(int i = 0 ;i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(1);
id = (String) JO.get("id");
img = (String) JO.get("img");
w1 = (String) JO.get("w1");
w2 = (String) JO.get("w2");
w3 = (String) JO.get("w3");
w4 = (String) JO.get("w4");
// }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int levelId = Integer.parseInt(id);
levelId++;
LevelActivity.levelID = String.valueOf(levelId);
LevelActivity.imageURL = img;
LevelActivity.button1Word = w1;
LevelActivity.button2Word = w2;
LevelActivity.button3Word = w3;
LevelActivity.button4Word = w4;
}
}
Thanks ^-^
I just needed to update the image and level text view number in onPostExecute method to make it load from the first time.
Answer by NIKHIL AGGARWAL

JSON extraction author guardian API

So, I'm trying to extract JSON from the Guardian newspaper API.
Basically I can get everything except the author which is crucial.
How do or what is a different way of extracting this.
Many thanks in advance I'm new to all this and have asked questions i n the past to no avail any advice would be greatly appreciated.
QueryUtils.Java
package com.example.android.newsapp;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class QueryUtils {
private static final String TAG = QueryUtils.class.getSimpleName();
public static Context context;
private QueryUtils() {
}
public static List<News> fetchNews(String requestUrl) {
URL url = createUrl(requestUrl);
String json_response = null;
try {
json_response = makeHttpRequest(url);
Log.i(TAG, json_response);
} catch (IOException e) {
e.printStackTrace();
}
List<News> news = extractFromJson(json_response);
return news;
}
private static URL createUrl(String StringUrl) {
URL url = null;
try {
url = new URL(StringUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String json_response = "";
if (url == null) {
return json_response;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
json_response = readFromString(inputStream);
} else {
Log.e(TAG, "Error" + httpURLConnection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return json_response;
}
private static String readFromString(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
} private static String extractString(JSONObject newInfo, String stringName) {
String str = null;
try {
str = newInfo.getString(stringName);
} catch (JSONException e) {
Log.e(TAG, context.getString(R.string.query_util_error_extract_string) + stringName);
}
if (str != null) {
return str;
} else {
return context.getString(R.string.empty_string);
}
}
private static List<News> extractFromJson(String news_json) {
if (TextUtils.isEmpty(news_json)) {
return null;
}
List<News> news = new ArrayList<News>();
try {
JSONObject baseJson = new JSONObject(news_json);
JSONArray news_array = baseJson.getJSONObject("response").getJSONArray("results");
for (int i = 0; i < news_array.length(); i++) {
JSONObject currentNews = news_array.getJSONObject(i);
String name = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
JSONArray tags = baseJson.getJSONArray("tags");
String contributor = null;
if (tags.length() == 1) {
JSONObject contributorTag = (JSONObject) tags.get(0);
contributor = extractString(contributorTag, context.getString(R.string.query_util_json_web_title));
} else {
//no contributor
contributor = context.getString(R.string.empty_string);
}
News mNews = new News(name, title, date, url, contributor);
news.add(mNews);
}
} catch (JSONException e) {
e.printStackTrace();
}
return news;
}
}
This is the JSON that I'm extracting from.
https://content.guardianapis.com/search?q=debate&tag=politics/politics&from-date=2014-01-01&api-key=test
This is the Data-Provider..
http://open-platform.theguardian.com/documentation/
I too had trouble getting the author. There were two changes I made that resolved the issue.
First, I did have to change the add the &show-tags=contributor to the url.
Second, I had to tweak your your if statement in parsing to read. Instead of :
contributor = extractString(contributorTag, context.getString(R.string.query_util_json_web_title));
I replaced with :
contributor = contributorTag.getString("webTitle");
(The key "webTitle" contains the author's name)
A problem for you is the url you used doesn't give the tag array which contains the webTitle key, even after I adjusted it with the &show-tags=contributor.
The url I used is:
http://content.guardianapis.com/search?&show-tags=contributor&q=%27tech%27&api-key=2bbbc59c-5b48-46a5-83d3-8435d3136348
The full QueryUtils.java file is:
package com.example.android.technewsapps1;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
/**
* Query the Guardian dataset and return a list of NewsStory objects.
*/
public static List<NewsStory> fetchNewsStoryData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create a list of NewsStories
List<NewsStory> newsStories = extractFeatureFromJson(jsonResponse);
// Return the list of NewsStories
return newsStories;
}
/**
* Returns new URL object from the given String URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the newsStory JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return a list of NewsStory objects that has been built up from
* parsing the given JSON response.
*/
private static List<NewsStory> extractFeatureFromJson(String newsStoryJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(newsStoryJSON)) {
return null;
}
// Create an empty ArrayList that we can start adding news stories to
List<NewsStory> newsStories = new ArrayList<>();
// Try to parse the JSON response string. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsStoryJSON);
//Create the JSONObject with the key "response"
JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");
//JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");
// Extract the JSONArray associated with the key called "results",
// which represents a list of news stories.
JSONArray newsStoryArray = responseJSONObject.getJSONArray("results");
// For each newsStory in the newsStoryArray, create an NewsStory object
for (int i = 0; i < newsStoryArray.length(); i++) {
// Get a single newsStory at position i within the list of news stories
JSONObject currentStory = newsStoryArray.getJSONObject(i);
// Extract the value for the key called "webTitle"
String title = currentStory.getString("webTitle");
// Extract the value for the key called "sectionName"
String sectionName = currentStory.getString("sectionName");
// Extract the value for the key called "webPublicationDate"
String date = currentStory.getString("webPublicationDate");
// Extract the value for the key called "url"
String url = currentStory.getString("webUrl");
//Extract the JSONArray with the key "tag"
JSONArray tagsArray = currentStory.getJSONArray("tags");
//Declare String variable to hold author name
String authorName = null;
if (tagsArray.length() == 1) {
JSONObject contributorTag = (JSONObject) tagsArray.get(0);
authorName = contributorTag.getString("webTitle");
}
// Create a new NewsStory object with the title, section name, date,
// and url from the JSON response.
NewsStory newsStory = new NewsStory(title, sectionName, date, url, authorName);
// Add the new NewsStory to the list of newsStories.
newsStories.add(newsStory);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the newsStory JSON results", e);
}
// Return the list of earthquakes
return newsStories;
}
}

How to use Microsoft Translator API in Android

The Microsoft Translator API for android samples has already been deprecated since march 2017 (just this yr). So I'm having a hard time translating text on android. Can anyone help me make this work on android?. It's just that I already have this working in java but I can't make it work on Android. I already tried using asynctask , but to no avail, no translation is being outputed. Or prolly I just did a wrong asyc task?.
The Interface of the application is like this:
It just have a simple textfield with translation that should be outputed on the other textfield. The translation is from Korean to English.
Github Project File is in here
https://github.com/iamjoshuabcxvii/MSTranslateAPIforAndroid
Android code is this.
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import org.apache.commons.io.IOUtils;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
//MS Translator Key is in here
public static String key = "<The MS Assigned Translator Key>";
private TextView txtTranslatedText, txtOriginalText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOriginalText = findViewById(R.id.txtOriginalText);
txtTranslatedText = findViewById(R.id.txtTranslatedText);
}
public void translate(View view) {
// String textOrig = txtOriginalText.getText().toString();
// String textOrig ="안녕하세요 123 -)^ 친구";
String textOrig;
textOrig=txtOriginalText.getText().toString();
String output;
output=getTranslation(textOrig);
txtTranslatedText.setText(output);
}
public static String getTranslation(String translatedTextStr) {
try {
// Get the access token
// The key got from Azure portal, please see https://learn.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
// System.out.println(token); //Code to Display Token
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
String text = URLEncoder.encode(translatedTextStr, "UTF-8");
String from = "ko";
String to = "en";
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid=%s&text=%s&from=%s&to=%s&maxTranslations=5", appId, text, from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("POST");
translateConn.setRequestProperty("Accept", "application/xml");
translateConn.setRequestProperty("Content-Type", "text/xml");
translateConn.setDoOutput(true);
String TranslationOptions = "<TranslateOptions xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">" +
"<Category>general</Category>" +
"<ContentType>text/plain</ContentType>" +
"<IncludeMultipleMTAlternatives>True</IncludeMultipleMTAlternatives>" +
"<ReservedFlags></ReservedFlags>" +
"<State>contact with each other</State>" +
"</TranslateOptions>";
translateConn.setRequestProperty("TranslationOptions", TranslationOptions);
IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
// System.out.println(resp+"\n\n");
String s=resp;
Pattern assign_op=Pattern.compile("(<TranslatedText>)"
+ "|(<\\/TranslatedText>)"
+ "|[()\\\\[\\\\]{};=#.,'\\\\^:#!$%&_`*-<>]"
+ "|[a-zA-Z0-9\\s]*"
+ "");
Matcher m = assign_op.matcher(s) ;
String actualTranslation="";
Boolean endOfTransTxt=false,startOfTransTxt=false,concat=false;
String foundRegexStr="",tempStr="";
while (m.find()) {
foundRegexStr=m.group();
if(m.group().matches("(<TranslatedText>)")) {
startOfTransTxt=true;
}
else if(m.group().matches("(<\\/TranslatedText>)")) {
endOfTransTxt=true;
concat=false;
}
else{
startOfTransTxt=false;
endOfTransTxt=false;
}
if(startOfTransTxt==true) {
concat=true;
}
else if(concat==true) {
tempStr=tempStr+""+m.group();
}
else {
}
}
// System.out.println("\nTranslated Text: "+tempStr);
translatedTextStr=tempStr;
} catch (Exception e) {
e.printStackTrace();
}
return translatedTextStr;
}
}
I think you did a wrong AsyncTask.
You can do it like this:
private class TransAsynTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... strings) {
String output = getTranslation(strings[0]);
return output;
}
#Override
protected void onPostExecute(String s) {
txtTranslatedText.setText("Output: " + s);
super.onPostExecute(s);
}
}
And in the onCreate you call:
String textOrig;
textOrig = txtOriginalText.getText().toString();
new TransAsynTask().execute(textOrig);
/*String output;
output = getTranslation(textOrig);
txtTranslatedText.setText("Translated Text: " + output);*/

Firebase user authentication for java application (Not Android)

I want to create a user authentication form for my java application using firebase. The dependencies for connection to the realtime database is available and the use of Firebase Admin is well documented here.
But presently Firebase Admin supports user authentication only for Node.js and it is documented here.
Here is my test code.
public class Login {
private JPanel jPanel;
public static void main(String[] args) {
// Show My Form
JFrame jFrame = new JFrame("Login");
jFrame.setContentPane(new Login().jPanel);
jFrame.pack();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setVisible(true);
// Firebase
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setServiceAccount(new FileInputStream("xxx.json"))
.setDatabaseUrl("https://xxx.firebaseio.com/")
.build();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (options != null) {
FirebaseApp.initializeApp(options);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Clip");
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("ClipText = [" + dataSnapshot.getValue() + "]");
}
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
Can anyone please guide me how can I create user authentication (e.g. Create user using email & password, Sign in) for my java application?
Note: I'm using Gradle.
Basing on the REST API documentation here: https://firebase.google.com/docs/reference/rest/auth/
i created a singleton like that to get a valid token from email and password and to validate it using the getAccountInfo method:
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class FireBaseAuth {
private static final String BASE_URL = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/";
private static final String OPERATION_AUTH = "verifyPassword";
private static final String OPERATION_REFRESH_TOKEN = "token";
private static final String OPERATION_ACCOUNT_INFO = "getAccountInfo";
private String firebaseKey;
private static FireBaseAuth instance = null;
protected FireBaseAuth() {
firebaseKey = "YOUR FIREBASE KEY HERE";
}
public static FireBaseAuth getInstance() {
if(instance == null) {
instance = new FireBaseAuth();
}
return instance;
}
public String auth(String username, String password) throws Exception {
HttpURLConnection urlRequest = null;
String token = null;
try {
URL url = new URL(BASE_URL+OPERATION_AUTH+"?key="+firebaseKey);
urlRequest = (HttpURLConnection) url.openConnection();
urlRequest.setDoOutput(true);
urlRequest.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = urlRequest.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("{\"email\":\""+username+"\",\"password\":\""+password+"\",\"returnSecureToken\":true}");
osw.flush();
osw.close();
urlRequest.connect();
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) urlRequest.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
token = rootobj.get("idToken").getAsString();
} catch (Exception e) {
return null;
} finally {
urlRequest.disconnect();
}
return token;
}
public String getAccountInfo(String token) throws Exception {
HttpURLConnection urlRequest = null;
String email = null;
try {
URL url = new URL(BASE_URL+OPERATION_ACCOUNT_INFO+"?key="+firebaseKey);
urlRequest = (HttpURLConnection) url.openConnection();
urlRequest.setDoOutput(true);
urlRequest.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = urlRequest.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("{\"idToken\":\""+token+"\"}");
osw.flush();
osw.close();
urlRequest.connect();
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) urlRequest.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
email = rootobj.get("users").getAsJsonArray().get(0).getAsJsonObject().get("email").getAsString();
} catch (Exception e) {
return null;
} finally {
urlRequest.disconnect();
}
return email;
}
}
This not allow you to create users dinamically but suppose to have them already created on Firebase

Android: JSON parsing error nothing comes up

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'
}

Categories