Calling api.ai from Android - android

I am building an android app in which I am calling api.ai. I want to parse the response and display it to users. Earlier I had written code in node.js which is as below:
function sendMessageToApiAi(options,botcontext) {
var message = options.message; // Mandatory
var sessionId = options.sessionId || ""; // optinal
var callback = options.callback;
if (!(callback && typeof callback == 'function')) {
return botcontext.sendResponse("ERROR : type of options.callback should be function and its Mandatory");
}
var nlpToken = options.nlpToken;
if (!nlpToken) {
if (!botcontext.simpledb.botleveldata.config || !botcontext.simpledb.botleveldata.config.nlpToken) {
return botcontext.sendResponse("ERROR : token not set. Please set Api.ai Token to options.nlpToken or context.simpledb.botleveldata.config.nlpToken");
} else {
nlpToken = botcontext.simpledb.botleveldata.config.nlpToken;
}
}
var query = '?v=20150910&query='+ encodeURIComponent(message) +'&sessionId='+context.simpledb.roomleveldata.c1+'&timezone=Asia/Calcutta&lang=en '
var apiurl = "https://api.api.ai/api/query"+query;
var headers = { "Authorization": "Bearer " + nlpToken};
botcontext.simplehttp.makeGet(apiurl, headers, function(context, event) {
if (event.getresp) {
callback(event.getresp);
} else {
callback({})
}
});
}
My Android code is as below:
package com.example.pramod.apidev;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity{
private Button listenButton;
private TextView resultTextView;
private EditText inputText;
private static String API_URL = "https://api.api.ai/api/query";
private static String API_KEY = "d05b02dfe52f4b5f969ba1257cffac37";
private static String query;
private static String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listenButton = (Button) findViewById(R.id.listenButton);
resultTextView = (TextView) findViewById(R.id.resultTextView);
inputText = (EditText)findViewById(R.id.inputText);
s = inputText.getText().toString();
query = "?v=20150910&query=hi" +"&sessionId=1480181847573api&timezone=Asia/Calcutta&lang=en";
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
URL url = new URL(API_URL + query + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
}
}
});
}
}
I need help in following:
(i) How can call the Api.ai since I am getting an error 401? Can some one tell how to exactly call Api.ai using the Node.js code?
(ii) How can parse the response and display it to users?
Thanks in advance

I'm connecting with api.ai from android app.
The steps to do are the following
1. Add the dependencies:
compile 'ai.api:libai:1.2.2'
compile 'ai.api:sdk:2.0.1#aar'
2. Create an activity implementing AIListener.
3. Declare AIService,and AIDataService:
private AIService aiService;
private AIDataService aiDataService;
4. Initialize config, services and add listener:
final ai.api.android.AIConfiguration config = new ai.api.android.AIConfiguration("API_KEY",
ai.api.android.AIConfiguration.SupportedLanguages.Spanish,
ai.api.android.AIConfiguration.RecognitionEngine.System);
// Use with text search
aiDataService = new AIDataService(this, config);
// Use with Voice input
aiService = AIService.getService(this, config);
aiService.setListener(this);
5. Execute async task to make request:
AIRequest aiRequest = new AIRequest();
aiRequest.setQuery(request);
//request--any string you want to send to chat bot to get there corresponding response.
if(aiRequest==null) {
throw new IllegalArgumentException("aiRequest must be not null");
}
final AsyncTask<AIRequest, Integer, AIResponse> task =
new AsyncTask<AIRequest, Integer, AIResponse>() {
private AIError aiError;
#Override
protected AIResponse doInBackground(final AIRequest... params) {
final AIRequest request = params[0];
try {
final AIResponse response = aiDataService.request(request);
// Return response
return response;
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
};
task.execute(aiRequest);
6. onResult method
Result result = response.getResult();
If the result is a string, the string with the response will be in:
String speech = result.getFulfillment().getSpeech();
Regards.
Nuria

You can refer the official documentation of integrating API.AI here -
https://github.com/api-ai/apiai-android-client
Happy coding.

Related

Getting problems when using MVP model to write a "login" App

I tried to write a "login" App using MVP model. And I use WAMP to build up my server. I'm sure that my php documents have no problem.
Here is the structure of my App:
enter image description here
And here are the files:
User.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
IUserBiz.java
package com.example.android.login.mvp.biz;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserBiz
{
public void login(String username, String password, OnLoginListener loginListener);
}
OnLoginListener.java
package com.example.android.login.mvp.biz;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface OnLoginListener
{
void loginSuccess(User user);
void loginFailed();
}
UserBiz.java
package com.example.android.login.mvp.biz;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public class UserBiz extends AppCompatActivity implements IUserBiz
{
private User user;
private OnLoginListener loginListener;
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
task.execute(test1Url);
}
/**
* Update the UI with the given earthquake information.
*/
private void updateUi(User mUser) {
if (mUser.getStatus()==1)
{
loginListener.loginSuccess(user);
} else
{
loginListener.loginFailed();
}
}
private class LoginAsyncTask extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
// Perform the HTTP request for earthquake data and process the response.
User mUser = Utils.fetchEarthquakeData(urls[0],user);
return mUser;
}
#Override
protected void onPostExecute(User result) {
if(result==null){
return;
}
updateUi(result);
}
}
}
Utils.java
package com.example.android.login.mvp.biz;
import android.text.TextUtils;
import android.util.Log;
import com.example.android.login.mvp.bean.User;
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.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
/**
* Utility class with methods to help perform the HTTP request and
* parse the response.
*/
public final class Utils {
/** Tag for the log messages */
public static final String LOG_TAG = Utils.class.getSimpleName();
/**
* Query the USGS dataset and return an {#link User} object to represent a single earthquake.
*/
public static User fetchEarthquakeData(String requestUrl, User user) {
// 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, user);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
// Extract relevant fields from the JSON response and create an {#link User} object
User earthquake = extractFeatureFromJson(jsonResponse);
// Return the {#link User}
return earthquake;
}
/**
* 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, "Error with creating 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, User user) 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("POST");
urlConnection.setDoOutput(true);
String params="app_user_name="+user.getUsername()+'&'+"app_password="+user.getPassword();
OutputStream out=urlConnection.getOutputStream();
out.write(params.getBytes());//post提交参数
out.flush();
out.close();
// 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 earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
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 an {#link User} object by parsing out information
* about the first earthquake from the input earthquakeJSON string.
*/
private static User extractFeatureFromJson(String earthquakeJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
// If there are results in the features array
if (baseJsonResponse.length() > 0) {
int status = baseJsonResponse.getInt("status");
// Create a new {#link User} object
User user=new User();
user.setStatus(status);
return user;
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
UserLoginPresenter.java
package com.example.android.login.mvp.presenter;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.biz.IUserBiz;
import com.example.android.login.mvp.biz.OnLoginListener;
import com.example.android.login.mvp.biz.UserBiz;
import com.example.android.login.mvp.view.IUserLoginView;
/**
* Created by zhy on 15/6/19.
*/
public class UserLoginPresenter {
private IUserBiz userBiz;
private IUserLoginView userLoginView;
public UserLoginPresenter(IUserLoginView userLoginView) {
this.userLoginView = userLoginView;
this.userBiz = new UserBiz();
}
public void login() {
userLoginView.showLoading();
userBiz.login(userLoginView.getUserName(), userLoginView.getPassword(), new OnLoginListener() {
#Override
public void loginSuccess(final User user) {
userLoginView.toMainActivity(user);
userLoginView.hideLoading();
}
#Override
public void loginFailed() {
userLoginView.showFailedError();
userLoginView.hideLoading();
}
});
}
public void clear() {
userLoginView.clearUserName();
userLoginView.clearPassword();
}
}
IUserLoginView.java
package com.example.android.login.mvp.view;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserLoginView
{
String getUserName();
String getPassword();
void clearUserName();
void clearPassword();
void showLoading();
void hideLoading();
void toMainActivity(User user);
void showFailedError();
}
UserLoginActivity.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
But I got something wrong like this:
enter image description here
I have no idea about it. How to solve it?
the issue is here
this.userBiz = new UserBiz();
UserBiz is an activity so activity gets their context when they are being started with Intent (by OS) but creating an object of an activity will not provide any contenxt hence the null exception at
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
// no context here due to new UserBiz
// getString required context
task.execute(test1Url);
}
Solution : you can use enums or static final constants to avoid context and also would be wise to substitute UserBiz as separate class instead of an activity

How can I use Asynctask in different Activities?

I am writing an App that connects to the Fitbit API correctly and pulls back the data I need. I have an Inner class that extends AsyncTask that lets me complete this. So for example, my MainActivity.java opens the Fitbit OAuth2 page and the user logs in. The user is then directed back to the UserActivity.java and their info is displayed.
I now want to add another Activity that pulls back the information for the Activities that they carried out. So, my question is, do I need to add another inner class in my ActivitiesActivity.java or is there some other way to get the data. I know people have used an Interface before but I'm not sure how they work with AsyncTask.
package com.jordan.fitbit_connect;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
String response_type = "token";
String client_id = "22CJH3";
String redirect_uri = "myapplication://login";
String scope = "activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight";
String url = "https://www.fitbit.com/oauth2/authorize?" + "response_type=" + response_type + "&client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&scope=" + scope;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
// CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
// customTabsIntent.launchUrl(this, Uri.parse(url));
connectToFitbit();
}
public void connectToFitbit()
{
Button btn = (Button)findViewById(R.id.btnConnect);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
customTabsIntent.launchUrl(getApplicationContext(), Uri.parse(url));
}
});
}
}
package com.jordan.fitbit_connect;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
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 TestActivity extends AppCompatActivity
{
//String to hold the data sent back by the Intent
String string;
//String to extract the token from 'string' above
private static String token;
//Strings to get the data from the JSON Object
public static String name, avatar, age, weight, height;
TextView username, txtAge, txtWeight, txtHeight, txtBMI;
float bmi;
ImageView imgViewAvatar;
//-------------------------------------- START onNewIntent()------------------------------------
/*
This method returns the URI from the Intent as an encoded String
*/
#Override
protected void onNewIntent(Intent intent)
{
string = intent.getDataString();
}
//-------------------------------------- END onNewIntent()--------------------------------------
//-------------------------------------- START onCreate()---------------------------------------
/*
Default method when the class is created
*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
onNewIntent(getIntent());
token = string.substring(string.indexOf("&access_token")+36,308);
Log.i("TAG", "Access Token: "+ token);
Log.i("TAG", "Data String: " + string);
//new JSONTask().execute("https://api.fitbit.com/1.2/user/-/sleep/date/2017-10-26.json");
//new JSONTask().execute("https://api.fitbit.com/1/user/-/activities/steps/date/today/6m.json");
new JSONTask().execute("https://api.fitbit.com/1/user/-/profile.json");
}
//-------------------------------------- END onCreate()-----------------------------------------
//-------------------------------------- START of inner class JSONTask -------------------------
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
username = (TextView)findViewById(R.id.txtUser);
imgViewAvatar = (ImageView)findViewById(R.id.imgViewAvatar);
txtAge = (TextView)findViewById(R.id.txtAge);
txtWeight = (TextView) findViewById(R.id.txtWeight);
txtHeight = (TextView) findViewById(R.id.txtHeight);
txtBMI = (TextView) findViewById(R.id.txtBMI);
}
//-------------------------------------- START doInBackground()-----------------------------
/*
This method is what happens on the background thread when the
app is running. It will
*/
#Override
protected String doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
try
{
URL url = new URL(params[0]);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(false);
connection.addRequestProperty("Authorization", "Bearer " + token);
connection.connect();
InputStream stream = (InputStream)connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) !=null)
{
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.toString();
}
return null;
}
//-------------------------------------- END doInBackground()-------------------------------
//-------------------------------------- START onPostExecute()------------------------------
#Override
protected void onPostExecute(String data)
{
super.onPostExecute(data);
Log.i("TAG", data);
try
{
//GET ALL THE JSON DATA
JSONObject allData = new JSONObject(data);
//GET THE USERNAME
JSONObject userObject = allData.getJSONObject("user");
name = userObject.getString("fullName");
username.append(" "+name);
//GET THE USER'S AVATAR
avatar = userObject.getString("avatar640");
Picasso.get().load(avatar).into(imgViewAvatar);
//GET THE USER'S AGE
age = userObject.getString("age");
txtAge.append(" "+age);
weight = userObject.getString("weight");
txtWeight.append(" "+weight);
float weightFloat = Float.parseFloat(weight);
height = userObject.getString("height");
txtHeight.append(" "+height);
float heightFloat= Float.parseFloat(height)/100;
bmi = (float)(weightFloat/(heightFloat * heightFloat));
if(bmi <= 16)
{
txtBMI.setTextColor(Color.YELLOW);
txtBMI.append(" "+ String.valueOf(bmi) + " - You are severely underweight!");
}
else if(bmi <= 18.5)
{
txtBMI.setTextColor(Color.GRAY);
txtBMI.append(" "+ String.valueOf(bmi) + " - You are underweight!");
}
else if(bmi <= 25)
{
txtBMI.setTextColor(Color.GREEN);
txtBMI.append(" "+ String.valueOf(bmi) + " - Your weight is normal");
}
else if(bmi <= 30)
{
txtBMI.setTextColor(Color.parseColor("#FFA500"));
txtBMI.append(" "+ String.valueOf(bmi) + " - You are overweight!");
}
else
{
txtBMI.setTextColor(Color.RED);
txtBMI.append(" " + String.valueOf(bmi) + " - You are obese!");
}
// for(int i =0; i< userObject.length(); i++) {
//3.DECLARE ANOTHER JSONOBJECT THAT EXTRACTS THE OBECT FROM THE SPECIFIED ARRAY
//JSONObject sleep = sleepArray.getJSONObject(i);
//4.Then use a getString to get the data from the object
//name = userObject.getString("firstName");
// Log.i("TAG",name);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
//-------------------------------------- END of inner class JSONTask ---------------------------
}
One of the methods using AsynTask in different Activities, creating a callback interface.
Create a callback interface
interface AsyncTaskListener<T> {
public void onComplete(T result);
}
Then in your MainActivity and TestActivity:
public class MainActivity extends AppCompatActivity
implements AsyncTaskListener<String> {
public void onComplete(String result) {
// your staff here
}
}
public class TestActivity extends AppCompatActivity
implements AsyncTaskListener<String> {
public void onComplete(String result) {
// your staff here
}
}
And add to your AsyncTask class:
public class JSONTask extends AsyncTask<String, String, String>
private AsyncTaskListener<String> listener;
public JSONTask (AsyncTaskListener<String> callback) {
this.listener = callback;
}
protected void onPostExecute(String result) {
listener.onComplete(result); // calling onComplate interface
}

Android get attribute value from xml

I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();

Use android sharedpreference in AsyncTask

I have been developing web pages with php and MySQL for years but am new to developing for Android projects. I have searched and read through all previous questions that I found concerning the subject but have not found the answer that works for my project. Currently when I run the app, all I get is errors and no download. I am posting the complete code for my Main Activity and ask if anyone can explain what I have done wrong. The data in sharedpreferences for UserId is a integer and the Date/session is a number string and the Email/eaddress is a string
package com.example.logintest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
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 MainActivity extends AppCompatActivity {
String IgidPreference = "IgidPreference";
String UserId = "userId";
String Date = "session";
//OR SHOULD THE DECLEARATION BE??
//public static final String UserId = "userId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new VerifyLogin().execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
});
}
public class VerifyLogin extends AsyncTask<String, Void, String> {
Context ctx;
SharedPreferences pref;
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
String eaddress = arg0[0];
String today = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?Email=" + URLEncoder.encode(eaddress, "UTF-8");
data += "&Date=" + URLEncoder.encode(today, "UTF-8");
link = "http://domain.com/verifylogin.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;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String userId = jsonObj.getString("user_id");
String session = jsonObj.getString("session");
String error_type = jsonObj.getString("error");
String error_msg = jsonObj.getString("error_msg");
if (error_type.equals("FALSE")) {
pref = context.getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(UserId, userId);
editor.putString(Date, session);
editor.apply();
Intent intent = new Intent(MainActivity.this, Account.class);
startActivity(intent);
} else if (error_type.equals("TRUE")) {
Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, error_msg, 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();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I know it has been some time since posting on the topic but I had to replace the computer, along with Android Studio and make all new project.
Here is what I have found to handle the original issue. I am putting comments inside the code to help anyone else who wants to use code for their next project.
public class LoginActivity extends Activity { //Standard Activity code
Button BtnLaunchSigninActivity; //Button to click
private EditText etLoginUserName, etLoginPassword; // data to submit
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etLoginUserName = (EditText) findViewById(R.id.etLoginUserName);
etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);
BtnLaunchSigninActivity = (Button) findViewById(R.id.btnLoginSignin);
BtnLaunchSigninActivity.setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnLoginSignin) {
signin(v);
}
}
};
public void signin(View v) {
String userName = etLoginUserName.getText().toString();
String passWord = etLoginPassword.getText().toString();
Toast.makeText(this, "Signing In...", Toast.LENGTH_SHORT).show();
new SignIn(this).execute(userName, passWord); // Send data to AsyncTask
}
private class SignIn extends AsyncTask<String, Void, String> {
private Context context; // context is for the SignIn()
SignIn(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String userName = arg0[0];
String passWord = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
link = "url/login.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result; // My php returns jsonobjects
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result; //turn object into string
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String status = jsonObj.getString("status");
String userid = jsonObj.getString("uid");
String hash = jsonObj.getString("security");
Log.d("tag", jsonObj.toString(4));
if (status.equals("Good")) {
Toast.makeText(context, "Sign In successful.", Toast.LENGTH_SHORT).show();
//YOU HAVE TO USE JSONSTR TO GET USERID AND SECHASH FOR UPDATING SHARED PREFERENCES
//DUE TO ANY POSSIBLE DELAYS OF PROCESSING doInBackground() SEND JSON TO NEXT ACTIVITY TO SET PREFERENCES
//ADD THE STRING TO THE INTENT BELOW, THEN PROCESS THE DATA FOR SETTING SHAREDPREFERENCES IN THE NEXT ACTIVITY
Log.d("UserID",userid);
Log.d("SecHash", hash);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Bundle extras = new Bundle();
extras.putString("USERID",jsonObj.getString("uid"));
extras.putString("SECHASH",jsonObj.getString("security"));
extras.putString("USERID","userid");
extras.putString("SECHASH","hash");
intent.putExtras(extras);
startActivity(intent);
} else if (status.equals("Wrong")) {
Toast.makeText(context, "Username/Password is incorrect, could not be verified. Sign In 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();
}
}
}
}
In next activity get the extras from the intent and add them to the sharedPreferences. That is all there is to it.
Thanks to everyone for their assistance before. I hope this will help others who find themselves with the same problem in the future.
In doInBackground() you define a locale variable but use a members variable
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
Since you only assign pref in onPostExecute() you'll get NullPointerExceptions everytime. Also ctx is null and context is not even declared. So make sure you have pref defined as early as possible.
public class VerifyLogin extends AsyncTask<String, Void, String> {
private final SharedPreferences pref;
VerifyLogin() {
pref = getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
}
[...]
}
But in the end you should not implement it like this at all. You'll leak your activity here!

How to know that specific document is present in Cloudant Database using Android App

I have successfully created document in Cloudant database through my Android App. But I can not find a specific document present in Cloudant database. What I have tried is like below....
TabTwo_Fragment.java
package com.example.android02.insightapp11;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DatastoreNotCreatedException;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentNotFoundException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.replication.Replicator;
import com.cloudant.sync.replication.ReplicatorBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* A simple {#link Fragment} subclass.
*/
public class TabTwo_Fragment extends Fragment implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String DATASTORE_MANGER_DIR = "data";
private static final String TASKS_DATASTORE_NAME = "tasks";
Datastore DataStore;
private Replicator PushReplicator, PullReplicator;
DocumentRevision revision;
static final String CLOUDANT_USER = "user_default";
static final String CLOUDANT_DB = "database_name";
static final String CLOUDANT_API_KEY = "api_key";
static final String CLOUDANT_API_SECRET = "api_key_pwd";
long TWITTER_ID = MainActivity.twitterID;
String TWITTER_NAME = MainActivity.userName;
Button btn_submit;
Spinner sp1, sp2, sp3, sp4, sp5, sp6, sp7, sp8;
TextView ans_total;
String user = "old";
HashMap<String, String> qa_hashmap;
public TabTwo_Fragment() {
// Required empty public constructor
}
public static TabTwo_Fragment newInstance() {
return new TabTwo_Fragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabtwo_fragment, container, false);
try {
init(rootView);
} catch (DocumentNotFoundException e) {
} catch (DocumentException e) {
} catch (URISyntaxException e) {
}
return rootView;
}
void init(View rootView) throws DocumentException, URISyntaxException {
Log.e("init: ", "in init");
find_view_by_id(rootView);
registerClickEvents();
defaultConfig();
checkForRegisteredUser();
}
void find_view_by_id(View rootView) {
Log.e("find_view_by_id: ", "in find_view_by_id");
btn_submit = (Button) rootView.findViewById(R.id.btn_submit);
sp1 = (Spinner) rootView.findViewById(R.id.sp1);
sp2 = (Spinner) rootView.findViewById(R.id.sp2);
sp3 = (Spinner) rootView.findViewById(R.id.sp3);
sp4 = (Spinner) rootView.findViewById(R.id.sp4);
sp5 = (Spinner) rootView.findViewById(R.id.sp5);
sp6 = (Spinner) rootView.findViewById(R.id.sp6);
sp7 = (Spinner) rootView.findViewById(R.id.sp7);
sp8 = (Spinner) rootView.findViewById(R.id.sp8);
ans_total = (TextView) rootView.findViewById(R.id.ans_total);
}
void registerClickEvents() {
Log.e("registerClickEvents: ", "in registerClickEvents");
btn_submit.setOnClickListener(this);
}
void defaultConfig() {
Log.e("defaultConfig: ", "in defaultConfig");
PreferenceManager.setDefaultValues(getContext(), R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPref.registerOnSharedPreferenceChangeListener(this);
File path = getContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
try {
DataStore = manager.openDatastore(TASKS_DATASTORE_NAME);
setUriPlusReplicators();
} catch (DatastoreNotCreatedException e) {
Toast.makeText(getContext(), "Unable to open Datastore!", Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e) {
Toast.makeText(getContext(), "URI Exception!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
setUriPlusReplicators();
} catch (URISyntaxException e) {
}
}
void setUriPlusReplicators() throws URISyntaxException {
Log.e("setUriPlusReplicators: ", "in setUriPlusReplicators");
URI uri = this.createServerUri();
Log.e("URI: ", "" + uri);
PushReplicator = ReplicatorBuilder.push().from(DataStore).to(uri).build();
PushReplicator.getEventBus().register(this);
PullReplicator = ReplicatorBuilder.pull().to(DataStore).from(uri).build();
PullReplicator.getEventBus().register(this);
}
private URI createServerUri() throws URISyntaxException {
Log.e("createServerUri: ", "in createServerUri");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName, null, null);
}
private URI createServerUri2(long twitterId) throws URISyntaxException {
Log.e("createServerUri2: ", "in createServerUri2");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName + "/_all_docs?", null, null);
}
void checkForRegisteredUser() throws DocumentNotFoundException, DocumentException, URISyntaxException {
BasicDocumentRevision retrieved = DataStore.getDocument(TWITTER_ID + "");
if (user.equals("new")) {
setQuizData(retrieved.getBody().toString());
} else {
newUser();
}
}
void setQuizData(String DataRetrieved) {
Log.e("setQuizData: ", "In setQuizData");
user = "old";
Log.e("DataRetrieved: ", "In " + DataRetrieved);
String[] ANSWERS = getResources().getStringArray(R.array.ans);
try {
JSONObject jsonObject = new JSONObject(DataRetrieved);
JSONObject jsonObject1 = jsonObject.getJSONObject("questions");
String qs1 = jsonObject1.getString("q1");
String qs2 = jsonObject1.getString("q2");
String qs3 = jsonObject1.getString("q3");
String qs4 = jsonObject1.getString("q4");
String qs5 = jsonObject1.getString("q5");
String qs6 = jsonObject1.getString("q6");
String qs7 = jsonObject1.getString("q7");
String qs8 = jsonObject1.getString("q8");
sp1.setSelection(Arrays.asList(ANSWERS).indexOf(qs1));
sp2.setSelection(Arrays.asList(ANSWERS).indexOf(qs2));
sp3.setSelection(Arrays.asList(ANSWERS).indexOf(qs3));
sp4.setSelection(Arrays.asList(ANSWERS).indexOf(qs4));
sp5.setSelection(Arrays.asList(ANSWERS).indexOf(qs5));
sp6.setSelection(Arrays.asList(ANSWERS).indexOf(qs6));
sp7.setSelection(Arrays.asList(ANSWERS).indexOf(qs7));
sp8.setSelection(Arrays.asList(ANSWERS).indexOf(qs8));
} catch (JSONException e) {
}
}
void newUser() {
Log.e("newUser: ", "In newUser");
user = "new";
}
void createDocument() throws DocumentException {
Log.e("createDocument: ", "In createDocument");
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.docId = TWITTER_ID + "";
gatherQAData();
/*HashMap<String, Object> map_main = new HashMap<String, Object>();*/
HashMap<String, Object> map = new HashMap<String, Object>();
ArrayList<HashMap<String, Object>> arrayTeachers = new ArrayList<>();
map.put("twitter_id", TWITTER_ID + "");
map.put("twitter_name", TWITTER_NAME);
map.put("questions", qa_hashmap);
/*arrayTeachers.add(map);*/
/*map_main.put("user", arrayTeachers);*/
rev.body = DocumentBodyFactory.create(map);
revision = DataStore.createDocumentFromRevision(rev);
PushReplicator.start();
}
void updateDocument() {
Log.e("updateDocument: ", "In updateDocument");
}
void gatherQAData() {
Log.e("gatherQAData: ", "In gatherQAData");
qa_hashmap = new HashMap<String, String>();
String a1, a2, a3, a4, a5, a6, a7, a8;
a1 = sp1.getSelectedItem().toString();
a2 = sp2.getSelectedItem().toString();
a3 = sp3.getSelectedItem().toString();
a4 = sp4.getSelectedItem().toString();
a5 = sp5.getSelectedItem().toString();
a6 = sp6.getSelectedItem().toString();
a7 = sp7.getSelectedItem().toString();
a8 = sp8.getSelectedItem().toString();
qa_hashmap.put("q1", a1);
qa_hashmap.put("q2", a2);
qa_hashmap.put("q3", a3);
qa_hashmap.put("q4", a4);
qa_hashmap.put("q5", a5);
qa_hashmap.put("q6", a6);
qa_hashmap.put("q7", a7);
qa_hashmap.put("q8", a8);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_submit:
if (user.equals("new")) {
try {
createDocument();
} catch (DocumentException e) {
}
} else {
updateDocument();
}
break;
default:
}
}
}
I can get the document which is stored in DataStore. But I am unable to get document stored in Cloudant database.
FYI: I am finding document in checkForRegisteredUser method.
Yes, I have done it. Below is my code for checkForRegisteredUser method of TabTwo_Fragment.java
void checkForRegisteredUser() {
String url = "https://your_cloudant_user_name.cloudant.com/" + DB_NAME + "/" + DOC_ID;
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response.toString().length() > 0) {
setQuizData(response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
newUser();
}
});
requestQueue.add(jor);
Here is s Official Documentation LINK.
Here DOC_ID is the id of document that you want to check. Hope this will help to somebody.
What happens in Cloudant is that there are already two fields by default given by cloudant to each document namely _id and _rev where _id acts as primarykey for indexing. So there will be a default index created by cloudant on the _id field. If you already have these fields in your document than cloudant won't insert extra _id and _rev.
Now you can have this _id field in your document and set it according to yourself or let cloudant set it. But when you are not setting it than you won't be able to query Cloudant on the primary index because you don't know the _id of the document.
So to search or find on basis of some other field like the twitter_id as you have stored you have to create one more index than you'll be able to search/find according to that.
we can create index in java using the function provided by cloudant api
public void createIndex(java.lang.String indexName,
java.lang.String designDocName,
java.lang.String indexType,
IndexField[] fields)
or If you are assigning _id in your function than you can simply call a function
db.contains(doc_id);
which is a lot easier as you don't need to create any index and using default index.
EDIT-1
So the db here is the database instance you have acquired.
Database db=client.database(db_name,create_flag);
where create_flag is a boolean to if the database should be created if not existed so true means yes create false means no don't create if not there.
and client is CloudantClient object.
But alternatively you can call createDB also if you know the db is not there. You can do it as follow
Database db=client.createDB("DBNAME");
How to get a CloudantClient is dependent on the version of cloudant api you are using. for ex 1.0.1 is different from the latest.
in version 1.0.1 you do it as follow
CloudantClient client=new CloudantClient(URL_OF_YOUR_CLOUDANT,USERNAME,PASSWORD);
But in latest release they use
CloudantClient client=ClientBuilder.url(new URL("your url")).username("your username string").password("your password").build();
SO I don't know why you were not able to find createIndex. I suppose you are unable to find Cloudant-api javadocs .Just google for Cloudant javadocs or check this github
GitHub link

Categories

Resources