RichRelevance SDK internally giving Null Pointer Exception. How to fix it? - android

// method to set the richRelevance configuration
public static void initializeRichRelevance(Context context) {
final SharedPreference sharedPreference = SharedPreference.getInstance(context);
ClientConfiguration config = new ClientConfiguration(APIKEY, CLIENTKEY);
config.setApiClientSecret("");
Log.e("Member_ID",getStringValue(sharedPreference.getSharedPref("member_id")));
config.setUserId(getStringValue(sharedPreference.getSharedPref("member_id")));
config.setSessionId(UUID.randomUUID().toString());
RichRelevance.init(context, config);
// Enable all logging
RichRelevance.setLoggingLevel(RRLog.VERBOSE);
Logger.logDebug("RichRelevance", "initilization Done...");
}
// method to fetch recommended product from richRelevance
private void initRichRelevance() {
RichRelevance.setLoggingLevel(RRLog.VERBOSE);
Placement placement = new Placement(Placement.PlacementType.ITEM, "recs_2mh");
PlacementsRecommendationsBuilder placementsRecommendationsBuilder = new PlacementsRecommendationsBuilder();
placementsRecommendationsBuilder.setPlacements(placement);
placementsRecommendationsBuilder.setProductIds(idProduct);
placementsRecommendationsBuilder.setCallback(new Callback<PlacementResponseInfo>() {
#Override
public void onResult(PlacementResponseInfo placementResponseInfo) {
JSONObject jsonObject = null;
if (placementResponseInfo != null && placementResponseInfo.getPlacements() != null) {
try {
jsonObject = new JSONObject(placementResponseInfo.getRawJson().toString());
requestAPI(jsonObject);
} catch (JSONException e) {
Utils.logExceptionCrashLytics(e);
Logger.logError("JsonException", e.getMessage());
}
}
}
#Override
public void onError(com.richrelevance.Error error) {
Log.e(getClass().getSimpleName(), "Error: " + error.getMessage());
}
}).execute();
}
Fatal Exception: java.lang.NullPointerException
at com.richrelevance.internal.net.HttpUrlConnectionExecutor.getConnection(HttpUrlConnectionExecutor.java:87)
at com.richrelevance.internal.net.HttpUrlConnectionExecutor.execute(HttpUrlConnectionExecutor.java:40)
at com.richrelevance.internal.net.WebRequestManager.execute(WebRequestManager.java:172)
at com.richrelevance.internal.net.WebRequestManager$1.run(WebRequestManager.java:193)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at com.richrelevance.internal.net.WebRequestManager$2$1.run(WebRequestManager.java:219)
at java.lang.Thread.run(Thread.java:841)

Related

Retrofit enqueue gets dismissed on orientation change

I am trying to upload plain text and image to the api using RetroFit. I want make sure the request continues to execute on orientation change. To do this, I have encapsulated the RetroFit api call inside a Headless fragment. This works fine when I try to upload an image. The request stops and resumes on device rotation. However it just gets cancelled on a text upload.
The only difference between the two uploads is that for image upload I use execute() and for text I use enqueue(). However, if I try to use execute() with the text, it still does not work.
Below is some code :-
UpdateTaskHelper (Headless fragment)
public static class UploadTaskHelper extends Fragment
{
private UploadAsync uploadTask;
private ProgressDialog m_loadingp;
public static UploadTaskHelper newInstance()
{
return new UploadTaskHelper();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDestroy()
{
Log.d(getClass().getName(), "[onDestroy]");
super.onDestroy();
if (uploadTask != null)
{
uploadTask.cancel(true);
}
}
public void startUpload(ActionActivity actionActivity, boolean shouldTakePhoto, boolean isTextNote, String noteContent)
{
uploadTask = new UploadAsync(actionActivity, shouldTakePhoto, isText, noteContent);
uploadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static class UploadAsync extends AsyncTask<Void, Void, Void>
{
private Bitmap m_bitmap = null;
private Pair<Boolean, String> m_errorPair;
private File m_uploadedFile = null;
private WeakReference<ActionActivity> m_weakActivity;
private boolean shouldTakePhoto;
private boolean isTextNote;
private java.io.File m_capturedImageFile;
UploadAsync(#NonNull ActionActivity activity, boolean shouldTakePhoto, boolean isTextNote, String textNoteContent)
{
this.m_weakActivity = new WeakReference<>(activity);
this.shouldTakePhoto = shouldTakePhoto;
this.isTextNote = isTextNote;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
final ActionActivity activity = this.m_weakActivity.get();
activity.m_fileAPIWrapper = new FileAPIWrapper(new IHttpEventTracker<File>()
{
#Override
public void getCallProgress(int progress) {}
#Override
public void onCallFail(#NonNull String cause, #NonNull Throwable t, #Nullable ResponseBody responseBody)
{
m_errorPair = new Pair<>(true, t.getLocalizedMessage());
}
#Override
public void onCallSuccess(#NonNull RealmList<File> models)
{
m_errorPair = new Pair<>(false, AppConstants.EMPTY_STRING);
m_uploadedFile = models.get(0);
}
});
if(!isTextNote)
{
final java.io.File storageDir = new java.io.File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + java.io.File.separator + activity.getPackageName()
+ java.io.File.separator + "-" + java.io.File.separator);
if (!storageDir.exists())
{
storageDir.mkdirs();
}
this.m_capturedImageFile = java.io.File.createTempFile("IMG_" + System.currentTimeMillis(), ".jpg", storageDir);
final FileOutputStream outStream = new FileOutputStream(this.m_capturedImageFile);
this.m_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
outStream.flush();
outStream.close();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
this.m_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
activity.m_fileAPIWrapper.postImage(RequestBody.create(MediaType.parse("image/jpeg"), stream.toByteArray()));
stream.flush();
stream.close();
}
else
{
activity.m_fileAPIWrapper.postTextNote(RequestBody.create(MediaType.parse("multipart/raw"), activity.m_addContentNoteEdit.getText()
.toString()));
}
}
catch (Exception e)
{
e.printStackTrace();
this.m_errorPair = new Pair<>(true, e.toString());
}
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
activity.m_loading.show();
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
}
}
}
Network calls :-
public void postImage(#NonNull RequestBody reqFile) {
if (m_eventTracker != null) {
final ResponseToken token = NetworkUtil.getAccessToken();
if (getService() != null && m_httpOperationWrapper != null && token != null) {
m_call = getService().postImage(token.getTokenType() + " " + token.getAccessToken(), NetworkUtil.X_VERSION,
"filename=IMG_" + System.currentTimeMillis(), "image/jpeg", reqFile);
m_httpOperationWrapper.initCall(m_call, this, true);
} else {
m_eventTracker.onCallFail(AppConstants.BAD_REQUEST, new Throwable("Something went wrong, Try again later!"), null);
}
}
}
/**
* Execute HTTP call to post a new text note.
*/
public void postTextNote(#NonNull RequestBody requestBody) {
if (m_eventTracker != null) {
final ResponseToken token = NetworkUtil.getAccessToken();
if (getService() != null && m_httpOperationWrapper != null && token != null) {
m_call = getService().postFile(token.getTokenType() + " " + token.getAccessToken(), NetworkUtil.X_VERSION,
"filename=" + token.getOwnerId() + "_text_note_" + System.currentTimeMillis(), "text/plain",
requestBody);
m_httpOperationWrapper.initCall(m_call, this);
} else {
m_eventTracker.onCallFail(AppConstants.BAD_REQUEST, new Throwable("Something went wrong, Try again later!"), null);
}
}
}
public void initCall(#NonNull Call<ContentResponse> call, #NonNull IHttpOperationCallback callback, final boolean isSynchronousCall) {
m_callback = callback;
try {
if (NetworkUtil.isNetworkAvailable()) {
if (isSynchronousCall) {
m_executeRequest(call);
} else {
m_enqueueRequest(call);
}
} else {
m_callback.onFailure(call, new Throwable(AppConstants.NO_INTERNET), null);
}
} catch (Exception e) {
m_callback.onFailure(call, e.fillInStackTrace(), null);
}
}
private void m_enqueueRequest(#NonNull Call<ContentResponse> call) {
call.enqueue(new Callback<ContentResponse>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(#NonNull Call<ContentResponse> call, #NonNull Response<ContentResponse> response) {
if (m_callback != null) {
if (!Util.isValidResponse(response)) {
String error = "Status: " + response.code() + " " + response.message();
m_callback.onFailure(call, new Throwable(
response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ? AppConstants.UNAUTHORIZED : error), response.errorBody());
return;
}
m_callback.onSuccess(call, response.body());
}
}
#Override
public void onFailure(#NonNull Call<ContentResponse> call, #NonNull Throwable t) {
if (m_callback != null) {
m_callback.onFailure(call, t, null);
}
}
});
}
#WorkerThread
private void m_executeRequest(#NonNull Call<ContentResponse> call) {
try {
Response<ContentResponse> response = call.execute();
if (m_callback != null) {
if (!Util.isValidResponse(response)) {
String error = "Status: " + response.code() + " " + response.message();
m_callback.onFailure(call,
new Throwable(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ? AppConstants.UNAUTHORIZED : error),
response.errorBody());
return;
}
//noinspection ConstantConditions
m_callback.onSuccess(call, response.body());
}
} catch (IOException | RuntimeException e) {
e.printStackTrace();
if (m_callback != null) {
m_callback.onFailure(call, e.fillInStackTrace(), null);
}
}
}
How can I get the same behaviour for the text note? Any help is appreciated.
When you use enqueue your request sent async, and the orientation change destroys the activity and cancels your response code scope.
You should consider move the request code into a ViewModel class which is part of the MVVM architecture. The ViewModel would make the request even after orientation change and keep the data inside it, then you could access its data after the activity is re-created.

Android Google Speech to text ApiStreamObserver show 'Uncaught exception in the SynchronizationContext. Panic!' error?

i am using Google speech to text api from my translate application. Here i initialize the ApiStreamObserver for StreamingRecognizeResponse it throw some error. Code is below,
Initialize SpeechClient like,
#SuppressLint("StaticFieldLeak")
private void InitValue() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
final InputStream stream = getResources().openRawResource(R.raw.transcribeapi);
ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream(stream);
mSpeechClient = SpeechClient.create(SpeechSettings.newBuilder()
.setCredentialsProvider(fixedCredentialsProvider)
.build());
GetAudioPermission();
initialized = true;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
StreamingRecognizeClient
ApiStreamObserver<StreamingRecognizeRequest> mRequestObserver;
mRequestObserver= mSpeechClient.streamingRecognizeCallable().bidiStreamingCall(new ApiStreamObserver<StreamingRecognizeResponse>() {
#Override
public void onNext(StreamingRecognizeResponse response) {
Log.d(TAG, "onNext: ");
/* int numOfResults = response.getResultsCount();
if( numOfResults > 0 ){
for (int i=0;i<numOfResults;i++){
Log.d(TAG, "onNext: "+response.getResults(i).getAlternatives(i));
}
}*/
}
#Override
public void onError(Throwable t) {
Log.d(TAG, "onError: "+t.getMessage());
}
#Override
public void onCompleted() {
Log.d(TAG, "onCompleted: ");
}
});
exception message;
onError: io.grpc.StatusRuntimeException: INTERNAL: Panic! This is a bug!
2019-03-20 17:30:32.485 25247-25293/com.logicvalley.translator E/ManagedChannelImpl: [Channel<1>: (speech.googleapis.com:443)] Uncaught exception in the SynchronizationContext. Panic!
java.lang.AbstractMethodError: abstract method "io.grpc.internal.ConnectionClientTransport io.grpc.internal.ClientTransportFactory.newClientTransport(java.net.SocketAddress, io.grpc.internal.ClientTransportFactory$ClientTransportOptions)"
at io.grpc.internal.CallCredentialsApplyingTransportFactory.newClientTransport(CallCredentialsApplyingTransportFactory.java:47)
at io.grpc.internal.InternalSubchannel.startNewTransport(InternalSubchannel.java:262)
at io.grpc.internal.InternalSubchannel.obtainActiveTransport(InternalSubchannel.java:215)
at io.grpc.internal.ManagedChannelImpl$SubchannelImpl.requestConnection(ManagedChannelImpl.java:1438)
at io.grpc.internal.PickFirstLoadBalancer.handleResolvedAddressGroups(PickFirstLoadBalancer.java:59)
at io.grpc.internal.AutoConfiguredLoadBalancerFactory$AutoConfiguredLoadBalancer.handleResolvedAddressGroups(AutoConfiguredLoadBalancerFactory.java:149)
at io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl$1NamesResolved.run(ManagedChannelImpl.java:1312)
at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:101)
at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:130)
at io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl.onAddresses(ManagedChannelImpl.java:1317)
at io.grpc.internal.DnsNameResolver$Resolve.resolveInternal(DnsNameResolver.java:325)
at io.grpc.internal.DnsNameResolver$Resolve.run(DnsNameResolver.java:225)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Still two days am working this project no examples on anywhere.Only kotlin examples are available.
Please anyone help me..
Advance thanks...

IBM Watson Tone Analyzer Gives Empty Response

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.

Trying to integrate the Sinch API for Voip getting exception

I am trying to integrate the Sinch API in android .
My VOIPClient. Java is like this
public class VOIPClient {
private static final String TAG = "VOIPClient";
private SinchClient mSinch;
private TTSHelper mTTS;
private Call mCurrentCall;
private BootService mContext;
private SinchClientBuilder mBuilder;
private NsdController mNsdController;
private final CallListener mCallListener = new CallListener() {
#Override
public void onCallProgressing(Call call) {
Log.d(TAG, "Call established at " + " Thusee");
}
#Override
public void onCallEstablished(Call call) {
Log.d(TAG, "Call established at " + call.getDetails().getEstablishedTime());
mTTS.speak("Call started", TTSHelper.UTTERANCE_VOIP_START);
JsonObject payload = new JsonObject();
payload.addProperty("Status", 0);
payload.addProperty("Call_status", 1);
if (mNsdController != null) {
mNsdController.sendCommand(20, payload);
}
}
#Override
public void onCallEnded(Call call) {
Log.d(TAG, "Call ended at " + call.getDetails().getEndedTime() + "caused by " + call.getDetails().getEndCause().toString());
mTTS.speak("Call ended", TTSHelper.UTTERANCE_VOIP_END);
mCurrentCall.hangup();
JsonObject payload = new JsonObject();
payload.addProperty("Status", 0);
payload.addProperty("Call_status", 1);
if (mNsdController != null) {
mNsdController.sendCommand(21, payload);
}
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> list) {
}
};
public VOIPClient(BootService context) {
mContext = context;
mTTS = TTSHelper.getInstance(context);
mBuilder = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext())
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT);
if (mNsdController != null)
mNsdController.initialize();
}
public void start() {
SharedPreferences prefs = mContext.getPreferences();
int userId = prefs.getInt(MerryClient.PREF_USER_ID, 0);
String mUserId;
if (userId > 0) {
mUserId = String.valueOf(userId);
mSinch = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext()).userId(mUserId)
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT).build();
mSinch.setSupportCalling(true);
mSinch.setSupportManagedPush(false);
SinchClientListener sinchClientListener = new SinchClientListener() {
#Override
public void onClientStarted(SinchClient sinchClient) {
Log.d(TAG, "Sinch Client starts: " + sinchClient.getLocalUserId());
mTTS.speak("Call ready", TTSHelper.UTTERANCE_VOIP_READY);
}
#Override
public void onClientStopped(SinchClient sinchClient) {
Log.d(TAG, "Sinch Client stops");
}
#Override
public void onClientFailed(SinchClient sinchClient, SinchError sinchError) {
Log.e(TAG, String.format("Sinch Client error %d: %s", sinchError.getCode(), sinchError.getMessage()));
mSinch.terminate();
mTTS.speak("Voice Over IP failed", TTSHelper.UTTERANCE_VOIP_FAIL);
}
#Override
public void onRegistrationCredentialsRequired(SinchClient sinchClient, ClientRegistration clientRegistration) {
Log.d(TAG, "Sinch Client requires registration");
}
#Override
public void onLogMessage(int i, String s, String s1) {
Log.d(TAG, s1);
}
};
mSinch.addSinchClientListener(sinchClientListener);
mSinch.getCallClient().setRespectNativeCalls(false);
mSinch.getCallClient().addCallClientListener(new SinchCallClientListener());
mCurrentCall = null;
mSinch.startListeningOnActiveConnection();
mSinch.start();
}
}
public void tearDown() {
if (mSinch != null) {
mSinch.stopListeningOnActiveConnection();
mSinch.terminate();
mSinch = null;
}
}
public void restart() {
tearDown();
start();
}
public void initiateCall(final String targetUserName) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
if (targetUserName != null) {
try {
Call call = callUser(targetUserName);
call.addCallListener(mCallListener);
mCurrentCall = call;
} catch (Exception e) {
Log.e(TAG, "Initiate VOIP call failed", e);
}
}
Looper.loop();
}
}).start();
}
public void answerCall() {
if (mCurrentCall != null) {
mCurrentCall.answer();
}
}
public void hangUpCall() {
if (mCurrentCall != null) {
mCurrentCall.hangup();
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
mTTS.speak("Incoming call from " + call.getRemoteUserId(), TTSHelper.UTTERANCE_VOIP_INCOMING);
call.addCallListener(mCallListener);
mCurrentCall = call;
// For testing only
answerCall();
}
}
public Call callUser(String userId) {
if (mSinch != null && mSinch.isStarted()) {
start();
}
if (mSinch == null) {
return null;
}
return mSinch.getCallClient().callUser(userId);
}
class CallerThread implements Runnable {
public String mtargetUserName;
CallerThread(String targetUserName) {
this.mtargetUserName = targetUserName;
}
#Override
public void run() {
Looper.prepare();
if (mtargetUserName != null) {
try {
Call call = callUser(mtargetUserName);
call.addCallListener(mCallListener);
mCurrentCall = call;
} catch (Exception e) {
Log.e(TAG, "Initiate VOIP call failed", e);
mContext.getAlexa().start();
}
}
Looper.loop();
}
}
}
When I try to call to other device then I am getting these kind of exceptions
Initiate VOIP call failed
java.lang.IllegalStateException: SinchClient not started
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.throwUnlessStarted(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.call(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(Unknown Source)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(Unknown Source)
at tw.com.test.cloud.VOIPClient.callUser(VOIPClient.java:272)
at tw.com.test.cloud.VOIPClient$CallerThread.run(VOIPClient.java:293)
at java.lang.Thread.run(Thread.java:818)
Also some times I am getting this exception
FATAL EXCEPTION: Thread-75
Process: tw.com.test.wear, PID: 1123
java.lang.IllegalThreadStateException: A Looper must be associated with this thread.
at com.sinch.android.rtc.internal.AndroidLooperCallbackHandler.<init>(Unknown Source)
at com.sinch.android.rtc.internal.client.InternalSinchClientFactory.createSinchClient(Unknown Source)
at com.sinch.android.rtc.DefaultSinchClientBuilder.build(Unknown Source)
at tw.com.test.cloud.VOIPClient.start(VOIPClient.java:109)
at tw.com.test.cloud.VOIPClient$2.onClientStopped(VOIPClient.java:124)
at com.sinch.android.rtc.internal.client.DefaultSinchClient.shutdown(Unknown Source)
at com.sinch.android.rtc.internal.client.DefaultSinchClient.terminate(Unknown Source)
at tw.com.test.cloud.VOIPClient.tearDown(VOIPClient.java:160)
at tw.com.test.nsd.NsdController.messageReceived(NsdController.java:570)
at tw.com.test.nsd.NsdConnection.run(NsdConnection.java:115)
at java.lang.Thread.run(Thread.java:818)
2 Days I tried my self, I can't able to solve this yet,
I am always getting these exception. Sometimes it will work for one time then I need to restart the app.
You have to start SinchClient sinchClient.start(); and take NOTE during production mode do not place in a plain text form your SINCH_APP_SECRET, because its a secret key, hackers will easily read or decompile your code.
public VOIPClient(BootService context) {
mContext = context;
mTTS = TTSHelper.getInstance(context);
mBuilder = Sinch.getSinchClientBuilder().context(mContext.getApplicationContext())
.applicationKey(CloudConfig.SINCH_APP_KEY)
.applicationSecret(CloudConfig.SINCH_APP_SECRET)
.environmentHost(CloudConfig.SINCH_ENVIRONMENT);
sinchClient.setSupportCalling(true);
sinchClient.start();
if (mNsdController != null)
mNsdController.initialize();
}

database connection with asynctask error

Hi I'm beginner at android so I hope that you would help me in details
I made connection to MySQL database with AsyncTask it's all good it connects well and I get my data from the database but the thing is when I turn off my database (database is on wamp) my app force closes and it gives this error:java.util.concurrent.timeoutexception
I will put the AsyncTask codes below
private void get_banners(final int pages) {
AsyncHttpPost post = new AsyncHttpPost("http://192.168.1.102/soton/new.php");
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City", MainActivity.sp.getString("City", ""));
body.addStringPart("Page", String.valueOf(pages));
body.addStringPart("Cate", "all");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if (e != null) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
if (!result.equals("")) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//you can toast the result here
//Toast.makeText(MainActivity.activity, result,Toast.LENGTH_LONG).show();
if (page == 0) {
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String, Object> hash_add = new HashMap<>();
hash_add.put("ID", object.getString("ID"));
hash_add.put("Username", object.getString("Username"));
hash_add.put("Title", object.getString("Title"));
hash_add.put("Description", object.getString("Description"));
hash_add.put("Price", object.getString("Price"));
hash_add.put("Tell", object.getString("Tell"));
hash_add.put("Email", object.getString("Email"));
hash_add.put("City", object.getString("City"));
hash_add.put("Cate", object.getString("Cate"));
hash_add.put("Img1", object.getString("Img1"));
hash_add.put("Img2", object.getString("Img2"));
hash_add.put("Img3", object.getString("Img3"));
hash_add.put("Date", object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
else {
Toast.makeText(MainActivity.activity,result,Toast.LENGTH_LONG).show();
}
}
});
}
Update: Stack Trace
FATAL EXCEPTION: AsyncServer
Process: com.morteza.newproject, PID: 3211
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.morteza.newproject.Frag_banners_all$3.onCompleted(Frag_banners_all.java:145)
at com.morteza.newproject.Frag_banners_all$3.onCompleted(Frag_banners_all.java:130)
at com.koushikdutta.async.http.AsyncHttpClient.invokeWithAffinity(AsyncHttpClient.java:527)
at com.koushikdutta.async.http.AsyncHttpClient.access$800(AsyncHttpClient.java:51)
at com.koushikdutta.async.http.AsyncHttpClient$7.run(AsyncHttpClient.java:534)
at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)
at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)
at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)
at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)
at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)
W/System.err: java.util.concurrent.TimeoutException
W/System.err: at com.koushikdutta.async.http.AsyncHttpClient$2.run(AsyncHttpClient.java:246)
W/System.err: at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)
W/System.err: at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)
W/System.err: at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)
W/System.err: at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)
W/System.err: at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)
Application terminated.
Problem soved i solved it by adding only an else to the code the currect code is below
private void get_banners(final int pages) {
AsyncHttpPost post = new AsyncHttpPost("http://192.168.1.102/soton/new.php");
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City", MainActivity.sp.getString("City", ""));
body.addStringPart("Page", String.valueOf(pages));
body.addStringPart("Cate", "all");
post.setBody(body);
try {
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if (e != null) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity, "server is offline", Toast.LENGTH_LONG).show();
e.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
//this is the answer
else {
if (!result.equals("")) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//you can toast the result here
//Toast.makeText(MainActivity.activity, result,Toast.LENGTH_LONG).show();
if (page == 0) {
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String, Object> hash_add = new HashMap<>();
hash_add.put("ID", object.getString("ID"));
hash_add.put("Username", object.getString("Username"));
hash_add.put("Title", object.getString("Title"));
hash_add.put("Description", object.getString("Description"));
hash_add.put("Price", object.getString("Price"));
hash_add.put("Tell", object.getString("Tell"));
hash_add.put("Email", object.getString("Email"));
hash_add.put("City", object.getString("City"));
hash_add.put("Cate", object.getString("Cate"));
hash_add.put("Img1", object.getString("Img1"));
hash_add.put("Img2", object.getString("Img2"));
hash_add.put("Img3", object.getString("Img3"));
hash_add.put("Date", object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(MainActivity.activity, result, Toast.LENGTH_LONG).show();
}
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}

Categories

Resources