I am using Tone Analyzer of IBM Watson in my Android Code,but i keep getting java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
Following is my code
public class MainActivity extends AppCompatActivity {
final ToneAnalyzer toneAnalyzer =
new ToneAnalyzer("2018-01-19");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject credentials = null; // Convert the file into a JSON object
try {
credentials = new JSONObject(IOUtils.toString(
getResources().openRawResource(R.raw.credentials), "UTF-8"
));
String username = credentials.getString("username");
String password = credentials.getString("password");
toneAnalyzer.setUsernameAndPassword(username, password);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button analyzeButton = (Button)findViewById(R.id.analyze_button);
analyzeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText userInput = (EditText)findViewById(R.id.user_input);
final String textToAnalyze = userInput.getText().toString();
ToneOptions options = new ToneOptions.Builder()
.addTone(Tone.EMOTION)
.html(false).build();
toneAnalyzer.getTone(textToAnalyze, options).enqueue(
new ServiceCallback<ToneAnalysis>() {
#Override
public void onResponse(ToneAnalysis response) {
Log.i("Hii", "onResponse: "+response.getDocumentTone());
List<ToneScore> scores = response.getDocumentTone()
.getTones()
.get(0)
.getTones();
String detectedTones = "";
for(ToneScore score:scores) {
if(score.getScore() > 0.5f) {
detectedTones += score.getName() + " ";
}
}
final String toastMessage =
"The following emotions were detected:\n\n"
+ detectedTones.toUpperCase();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(),
toastMessage, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(Exception e) {
e.printStackTrace();
}
});
}
});
}
}
Can somebody point out what am i doing wrong. I have kept my credentials.json file in raw folder.
I tried writing every emotion in my Android App but i keep getting no response. Any help would be greatly appreciated.
Related
public void getTerms(boolean showDialog) {
service.getTermsFromServer().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleSubscriber<String>() {
#Override
public void onSuccess(String value) {
try {
JSONObject jsonObject = new JSONObject(value);
JSONObject data = jsonObject.getJSONObject("data");
String content = data.getString("content");
String id = data.getString("id");
if (showDialog) {
***signUpView.showDialog(content, id)***;
} else {
agreeTerms(id);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable error) {
Log.e(getClass().getName(), "Error : " + new Gson().toJson(error.getStackTrace()));
ErrorCheck.processError(error, gson, signUpView);
}
});
}
Please help me in testing this code. I have attached the method which i want to test. Here I want to verify that showDialog method gets called
Attaching the Unit test code also
#Test
public void testGetTermsCalled(){
String terms= "{\"data\":{\"id\":\"67f07c7a482542\",\"content\":\"<h3>Part of the test</h3>\",\"timestamp\":1484768675815,\"timestampFormatted\":\"2017-01-18T19:44:35\"},\"metadata\":null,\"version\":{\"id\":\"v1\",\"versionStatus\":\"candidate\",\"message\":null}}";
TestSubscriber<String> testSubscriber = new TestSubscriber<>();
signUpService.getTermsFromServer().just(terms).subscribe(testSubscriber);
signUpPresenter.getTerms(true);
Mockito.verify(signUpView).showDialog("<h3>Part of the test</h3>","67f07c71-1707-4b7a-a168-d7d05a482542");
}
Thanks!!!
Use RxJavaPlugins.setInitIoSchedulerHandler and RxAndroidPlugins.registerSchedulersHook to specify your own TestScheduler, then use its advanceTimeBy method to make some time pass, then verify that the expected calls happened.
I am basically trying to send a message from my android to my server and the server to send back a response to my android app. I followed THIS tutorial.
Just a simple exercise to introduce myself in to SignalR using Azure Web API and Android.
My Complete Server code in C#:
public class TestHub: Hub {
public void SendMessage(string name, string message) {
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
public void SendClientMessage(CustomType obj) {
Clients.All.broadcastMessage("From Server", "Server got the message bro");
}
public class CustomType {
public string Name;
public int Id;
}
}
Complete Android Java code:
public class MainActivity extends AppCompatActivity {
Handler handler;
TextView statustext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
statustext = (TextView) findViewById(R.id.status);
Platform.loadPlatformComponent(new AndroidPlatformComponent());
// Change to the IP address and matching port of your SignalR server.
String host = "https://My-Service-name.azure-mobile.net/";
HubConnection connection = new HubConnection(host);
HubProxy hub = connection.createHubProxy("TestHub");
SignalRFuture < Void > awaitConnection = connection.start();
try {
awaitConnection.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
hub.subscribe(this);
try {
hub.invoke("SendMessage", "Client", "Hello Server!").get();
hub.invoke("SendClientMessage",
new CustomType() {
{
Name = "Android Homie";
Id = 42;
}
}).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
//I have no idea what the following method is for. Just followed the tutorial.. (blindly)
public void UpdateStatus(String status) {
final String fStatus = status;
handler.post(new Runnable() {
#Override
public void run() {
statustext.setText(fStatus);
}
});
}
public class CustomType {
public String Name;
public int Id;
}
}
Problems with this:
1. I get an exception:
java.util.concurrent.ExecutionException:
microsoft.aspnet.signalr.client.transport.NegotiationException: There
was a problem in the negotiation with the server
2. I feel like I haven't properly called the server from the Java code.
Should the URL be:
https://My-Service-name.azure-mobile.net/
or
https://My-Service-name.azure-mobile.net/api/signalr
Can someone clarify these doubts and help me set it up?
I have made a demo for sending image to private chat using QuickBlox, I am struggling to attach an image with the chat message, I have gone through its document and have used the below Links, with no luck
Attach an image
My code is as below:
chatMessage = new QBChatMessage();
sendButton = (Button) findViewById(R.id.chatSendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String messageText = messageEditText.getText().toString();
if (TextUtils.isEmpty(messageText)) {
return;
}
// Send chat message
//
// send a message
// ...
int fileId = R.raw.ic_launcher;
InputStream is = ChatActivity.this.getResources()
.openRawResource(fileId);
File file = FileHelper.getFileInputStream(is,
"sample_file.png", "myFile");
Boolean fileIsPublic = true;
QBContent.uploadFileTask(file, fileIsPublic, messageText,
new QBEntityCallbackImpl<QBFile>() {
#Override
public void onSuccess(QBFile qbFile, Bundle params) {
String publicUrl = qbFile.getPublicUrl();
System.out
.println("==========image uploaded success++++++++"
+ publicUrl);
id = qbFile.getId();
System.out
.println("===================image id+++++++++++"
+ id + "");
}
#Override
public void onError(List<String> errors) {
System.out
.println("==========image uploaded Errors++++++++"
+ errors.toString());
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
QBAttachment atach = new QBAttachment("image");
atach.setId(id+"");
ArrayList<QBAttachment> aryatch = new ArrayList<QBAttachment>();
aryatch.add(atach);
chatMessage.setAttachments(aryatch);
chatMessage.setBody(messageText);
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(new Date().getTime() / 1000);
try {
chat.sendMessage(chatMessage);
} catch (XMPPException e) {
Log.e(TAG, "failed to send a message", e);
} catch (SmackException sme) {
Log.e(TAG, "failed to send a message", sme);
}
messageEditText.setText("");
if (dialog.getType() == QBDialogType.PRIVATE) {
showMessage(chatMessage);
}
}
});
Well it clear where the mistake is
your id is null here
atach.setId(id+"");
because it will != nil only in onSuccess block of uploadFileTask
So the right way is to forward all attachments logic inside onSuccess block of uploadFileTask
Because these QuickBlox request are asynchronous
Let's say I have this Dashboard.java:
public class DashboardActivity extends ActionBarActivity {
private TextView login_response;
private static String TAG = DashboardActivity.class.getSimpleName();
final static String API_URL_ACCOUNT = "http://www.example.com/apiv2/account";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
login_response = (TextView) findViewById(R.id.login_response);
Intent intent = getIntent();
if(intent.hasExtra("TOKEN"))
{
String token = intent.getStringExtra("TOKEN");
getShopName(token);
}
else
{
}
And this is the getShopName method:
private void getShopName(String token) {
JsonObjectRequest req = new JsonObjectRequest(API_URL_ACCOUNT + "?token=" + token, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
JSONArray account = response.getJSONArray("account");
//Log.d(TAG, "Account: "+account.toString());
JSONObject shop = account.getJSONObject(0);
String name_shop = shop.getString("name_shop");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
VolleyController.getInstance().addToRequestQueue(req);
}
My goal is to have
if(intent.hasExtra("TOKEN"))
{
String token = intent.getStringExtra("TOKEN");
String shop_name = getShopName(token);
}
The "shop_name" in variable, to reuse in other part.
So, I know that void doesn't return nothing, but, I tried to edit like this answer, without success:
How can I return value from function onResponse of Volley?
Thank you
The issue is not returning a value from a JsonObjectRequest, but rather that you're trying to do an asynchronous operation in a synchronous way.
Here is a great explanation: Asynchronous vs synchronous execution, what does it really mean?
And to your specific question: I advise using an AsyncTask for your network operation.
It is possible to load all history message according to custom parameter.
Currently we set a according to setPageLimit. But i want to use a custom parameter. . Custom parameter is sh_id,sh_r_id,customer_id, date
private void loadHistory(String dialogId){
QBDialog qbDialog = new QBDialog(dialogId);
QBRequestGetBuilder customObjectRequestBuilder = new QBRequestGetBuilder();
customObjectRequestBuilder.setPagesLimit(150);
QBChatService.getDialogMessages(qbDialog, customObjectRequestBuilder, new QBEntityCallbackImpl<ArrayList<QBChatHistoryMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatHistoryMessage> messages, Bundle args) {
try {
qbShopAdpt = new QBShopkeeperChatAdapter(mContext, new ArrayList<QBMessage>(),customer_id,sh_r_id1);
qbchatlv.setAdapter(qbShopAdpt);
for(QBMessage msg : messages) {
if(customer_id.equals(msg.getProperty("customer_id")) && sh_r_id1.equals(msg.getProperty("sh_r_id")) && SessionManager.getSignIn(mContext).getId()==Integer.valueOf(msg.getProperty("sh_id"))){
showMessage(msg);
}
}
} catch (NullPointerException e) {
Log.e(Tag, e.toString());
}catch (NumberFormatException e) {
Log.e(Tag, e.toString());
}catch (Exception e) {
Log.e(Tag, e.toString());
}
hideProgress();
}
#Override
public void onError(List<String> errors) {
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setMessage("load chat history errors: " + errors).create().show();
}
});
}
Try by this code for save chat may be this i am not shure
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1");
get chat by this
QBDialog qbDialog = new QBDialog("53cfc593efa3573ebd000017");
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setPagesLimit(100);
QBChatService.getDialogMessages(qbDialog, customObjectRequestBuilder, new
QBEntityCallbackImpl<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> messages, Bundle args) {
}
#Override
public void onError(List<String> errors) {
}
});
Try By this code it may be help you try by this link.
Here is Link