How to save the value of json response in shared preference? - java

I have to hit a json service and if the response came true than I have to save the user value in shared preference for future use. How can i do that?
my url is:
http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id={aff_id}
Variables will be passed by the sdk user. In the above url my variables are- id: 4 and public_key: 9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G
I have made a class and declared a static method. Inside the static method I have to do parsing and save the variables in shared preference.
public class InitializeSDK {
public static void init(final Context ctx, int id, String public_key){
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... unused) {
return null;
}
protected void onPostExecute(Void unused) {
}
}.execute();
}
}
Please tell me how to parse it to get the response and save it in shared preference?

Here is a sample code you can use:
protected Void doInBackground(Void... unused) {
//TODO: add code to read http request and store the json data in json variable
JSONObject jsonObject = new JSONObject(json);
boolean state = jsonObject.getBoolean("success");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putBoolean("state",state);
editor.commit();
return null;
}

Firstly, I suggest you need to get JSON data as a string and you can parse it.
String json = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id=");
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
data = reader.read();
json += currentChar;
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return json;
}
I call this method inside the doInBackground.

Related

how to get data from url in android studio

I want to get data from url and show in a textView , But after receiving, it only shows html codes.
I use a Educational video but my result is wrong.
I used another methods too but all result are same and just show html codes.
MainActivity :
public static final String SAMPLE_URL = "http://nimatest.epizy.com/ffff.json";
findViewById(R.id.btn_get_data).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskGetData().execute(SAMPLE_URL);
}
});
public class TaskGetData extends AsyncTask<String , String , String>{
#Override
protected void onPreExecute() {
textView.append("Get data ...\n\n");
}
#Override
protected String doInBackground(String... params) {
return MyHttpUtils.getDataHttpUriConnection(params[0]);
}
#Override
protected void onPostExecute(String result) {
textView.append(result + "\n");
}
}
MyHttpUtils :
public static String getDataHttpUriConnection(String uri){
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String result = inputStreamToString(con.getInputStream());
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String inputStreamToString(InputStream stream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = "";
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line);
sb.append("\n");
}
return sb.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
Your code is fine. It reads HTML from a URL
This site requires Javascript to work
HttpUrlConnection does not use or render dynamic Javascript created web pages, only static html content
Try a different endpoint for JSON data...
Also, please look into using a proper HTTP library for Android rather than using AsyncTask like Okhttp or Volley

Value Connection of type java.lang.String cannot be converted to JSONObject in getting objects from the database

I am trying to retrieve json records from the database. On retrieving the GET request over the browser my json responce is of this structure and returning appropriate data
[{"name":"OOGOGOGO","address":"OPOPOPOP","gender":"OPOPOPOP","email":"OPOPOPOP","phonenumber":"OPOPOPOP","nationality":"OPOOPOPO","fk":1}]
I am calling the endpoint url in the assync task doinbackground and this is the endpoint
url = new URL("http://10.0.2.2:88/example/web/app_dev.php/get/1");
the above endpoint returns 405 status code error. On attempting to catch a json exception I get this error
error gotten org.json.JSONException: Value Connection of type java.lang.String cannot be converted
confused on what could be wrong with this endpoint as it returns a 200 ok json response from postman. Kindly assist
Here's the code snippet.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Fetch network data
new NetworkAsyncTask().execute("http://www.mocky.io/v2/591f32f4110000d10307b4c7");
}
private class NetworkAsyncTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(String result) {
if (result != null) {
Log.d("TAG", "Success! Result: " + result);
processResult(result);
} else {
Log.d("TAG", "Failed, no data");
}
}
private void processResult(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject nameObject = jsonArray.getJSONObject(0);
String name = nameObject.optString("name");
Log.d("TAG", "name: " + name);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
For more information on networking and JSON on Android, i suggest you read this guide:
https://guides.codepath.com/android/Sending-and-Managing-Network-Requests
https://guides.codepath.com/android/Converting-JSON-to-Models

Using AsyncTask with passing a value

I have been working on this and I have hit a point where I dont know what to do. What I am trying to do is use one class to download and parse out a file into a string and then send that string to another class to parse out the JSON stuff. All the parts work fine by themselves and I have tested everything separately. I just dont know how to send the value to the Json parses to start the parsing.
So this is my filedownloader class.
public class JsonFileDownloader extends AsyncTask<String, Void, String> {
//used to access the website
String username = "admin";
String password = "admin";
public String ret = "";
#Override
protected String doInBackground(String... params) {
Log.d("Params ", params[0].toString());
readFromFile(params[0]);
return ret;
}
private String readFromFile(String myWebpage) {
HttpURLConnection urlConnection = null;
try {
//Get the url connection
URL url = new URL(myWebpage);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
ret = streamToString(inputStream);
inputStream.close();
Log.d("Final String", ret);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
return ret;
}
}
public static String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
public String getJsonData()
{
return ret;
}
}
This works fine I have tested it over and over with no errors.
The next is the Json parser which is like this.
public class JSONParser {
JSONObject jsonResponse;
String jsonData;
//Consturctor
public JSONParser()
{
//this.jsonData = jsonData;
// this.OutputData = outPutData;
}
public void parsesData(String promo,
ArrayList<String> pictureHTTP,
ArrayList<String> pathHTTP,
ArrayList<String> labelText) throws IOException {
//Build the Json String
JsonFileDownloader jfd = new JsonFileDownloader();
// jsonData = String.valueOf(jfd.execute(promo));
jfd.execute(promo);
//jfd.getResuts(jsonData);
//jsonData = jfd.ret;
Log.d("JsonData String = " , jsonData);
//Try to parse the data
try
{
Log.d("Jsondata " , jsonData);
//Creaate a new JSONObject ith the name/value mapping from the JSON string
jsonResponse = new JSONObject(jsonData);
//Returns the value mapped by the name if it exists and is a JSONArry
JSONArray jsonMainNode = jsonResponse.optJSONArray("");
//Proccess the JSON node
int lenghtJsonArrar = jsonMainNode.length();
for (int i = 0; i<lenghtJsonArrar; i++)
{
//Get object for each json node
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//Get the node values
//int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());
String picture = jsonChildNode.optString("picture").toString();
String pathName = jsonChildNode.optString("path").toString();
String lableName = jsonChildNode.optString("label".toString());
//Debug Testing code
pictureHTTP.add(picture);
pathHTTP.add(pathName);
labelText.add(lableName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Now I know where the problem is occurring. When i try to assign a value to the jsonData it never is assigned so it is null and the system fails.
I have tried a few things after the jfd.exicute() but I just dont know how to get the value from the final string output into the jsonData.
Thank you for any help with this.
Alright, here is a pretty flexible pattern for the overall usage of using AsyncTask to download web content and getting the results from it back to the UI thread.
Step 1 Define an interface that will act as a message bus between the AsyncTask and where you want the data.
public interface AsyncResponse<T> {
void onResponse(T response);
}
Step 2 Create a generic AsyncTask extension that will take any URL and return the results from it. You basically had this already, but I made some tweaks. Most importantly, allowing the setting of the AsyncResponse callback interface.
public class WebDownloadTask extends AsyncTask<String, Void, String> {
private AsyncResponse<String> callback;
// Optional parameters
private String username;
private String password;
// Make a constuctor to store the parameters
public WebDownloadTask(String username, String password) {
this.username = username;
this.password = password;
}
// Don't forget to call this
public void setCallback(AsyncResponse<String> callback) {
this.callback = callback;
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
return readFromFile(url);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (callback != null) {
callback.onResponse(s);
} else {
Log.w(WebDownloadTask.class.getSimpleName(), "The response was ignored");
}
}
/******* private helper methods *******/
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
private String readFromFile(String myWebpage) {
String response = null;
HttpURLConnection urlConnection = null;
try {
//Get the url connection
URL url = new URL(myWebpage);
// Unnecessary for general AsyncTask usage
/*
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
*/
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
response = streamToString(inputStream);
inputStream.close();
Log.d("Final String", response);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return response;
}
}
Step 3 Go forth and use that AsyncTask wherever you wish. Here is an example. Note that if you do not use setCallback, you will be unable to get the data that came from the AsyncTask.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebDownloadTask task = new WebDownloadTask("username", "password");
task.setCallback(new AsyncResponse<String>() {
#Override
public void onResponse(String response) {
// Handle response here. E.g. parse into a JSON object
// Then put objects into some list, then place into an adapter...
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
});
// Use any URL, this one returns a list of 10 users in JSON
task.execute("http://jsonplaceholder.typicode.com/users");
}
}

Not able to read a specific JSON url using socket in Android

I want to read a Json URL using sockets and display it in a textbox.
When I use URLs other than my given URL, it shows the output file. But its not the same case with my URL. The content in the URL is very large (around 184,523 characters).
Here is the code that I am using:
public class MainActivity extends Activity {
URLConnection feedUrl = null;
String json="";
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, Void>(){
#Override
protected void onPreExecute() {
txt=(TextView)findViewById(R.id.myresponse);
txt.setText("intialize");
}
#Override
protected Void doInBackground(Void... params) {
URLConnection feedUrl;
try {
feedUrl = new URL("http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week").openConnection();
InputStream is = feedUrl.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
json= sb.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
txt.setText(json);
}
}.execute();
}
}
The URL is http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week. Please can someone tell why it is not running?
One more question: What should I do if I want to print only a specified object of the JSON file.
For example, if I want to print the entire 5th object instead of the whole file. What should I do in that case?
First you have to format the result so you can get the actual JSON:
Matcher matcher = Pattern.compile(Pattern.quote("callback(") + "(.*?)" + Pattern.quote(");")).matcher(json);
while (matcher.find())
json = matcher.group(1);
After you get the formated json you need to transform it into a JSONObject
try{
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("features"); //get the features array
JSONObject myObject= array.getJSONObject(5); //get the element 5
}catch(Exception e){
e.printStackTrace();
}
Now you have a jsonobject called myObject with the 5th feature.

Cannot connect to vtiger database

I am trying to implement vtiger's API to connect my android application to it's server. I have added the API to the libs folder and then compile the .jar file. I then use the documentation to connect to the server in java.
boolean result = true;
WSClient client = new WSClient("http://en.vtiger.com/wip");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
result = client.doLogin("username", "Accesskey");
if(!result)
{
System.out.println("Login failed!");
System.out.println(client.lastError());
}
else
{
System.out.println("Login Successful");
}
}
However, I always get the Login failed and no error present. The problem is that when I open the WSClient.java class from inside the .jar, the program states that no sources can be found. I have downloaded these files from http://forge.vtiger.com/frs/?group_id=181&release_id=573 and do not know what to attach as a source. Maybe this is why I cannot connect to the server since I am using the right username and access key supplied by vtiger.
Try this:-
Its an example based on https://demo.vtiger.com/ for login
public class Login extends Activity {
//URL to get JSON Array
private static String url = "https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
// contacts JSONArray
JSONArray contacts = null;
String token = null;
String sessionId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog = new ProgressDialog(Login.this);
protected void onPreExecute() {
dialog.setMessage("Loging In... Please wait...");
dialog.show();
}
#SuppressWarnings("unused")
JSONObject result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONObject(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
String username="admin";
String accesskeyvalue = "w9OweWKUS4a5sSL";
String accessKey=md5(token + accesskeyvalue);
//For debugging purpose only
//System.out.println(accesskeyvalue);
//System.out.println(token);
//System.out.println(accessKey);
String data = null;
try {
data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("accessKey", "UTF-8") + "="
+ URLEncoder.encode(accessKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
//System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("https://demo.vtiger.com/webservice.php?operation=login");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response
System.out.println(text);
sessionId = text.substring(41, 62);
//System.out.println("doInBackground()"+sessionId);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
}
}.execute();
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
Change the variables as per your need
you don't need to use any additional jar files.

Categories

Resources