AWS AppSync Android NullPointerException - android

public void queryData(){
if(mAWSAppSyncClient == null){
mAWSAppSyncClient = ClientFactory.getInstance(this);
}
mAWSAppSyncClient.query(GetCounterDataQuery.builder().build())
.responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
.enqueue(postsCallback);
}
public GraphQLCall.Callback<GetCounterDataQuery.Data> postsCallback = new GraphQLCall.Callback<GetCounterDataQuery.Data>() {
#Override
public void onResponse(#Nonnull final Response<GetCounterDataQuery.Data> response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(response.data()!=null) {
TextView value = (TextView) findViewById(R.id.counterValue);
value.setText(response.data().getCounterData().counterData);
TextView Name = (TextView) findViewById(R.id.counterName);
Name.setText(response.data().getCounterData().counterName);
}
}
});
}
In the GraphQL Callback method, response.data() I am getting NullPointerException.(Even though I am using if condition to check null ) How to resolve?
Thanks for the replies,
Now its working fine with this solution, In response callback I have added some value if the response is NULL, it wouldn't be null in my case.
public void queryData(String id){
if(mAWSAppSyncClient == null){
mAWSAppSyncClient = ClientFactory.getInstance(this);
}
mAWSAppSyncClient.query(GetCounterQuery.builder().id(id).build())
.responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
.enqueue(postsCallback);
}
public GraphQLCall.Callback<GetCounterQuery.Data> postsCallback = new GraphQLCall.Callback<GetCounterQuery.Data>() {
#Override
public void onResponse(#Nonnull final Response<GetCounterQuery.Data> response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(response != null) {
String valuestr = (response.data().getCounter().counterNumber != NULL ) ? (response.data().getCounter().counterNumber).toString() : "66";
TextView value = (TextView) findViewById(R.id.counterValue);
value.setText(valuestr);
String nameStr= (response.data().getCounter().counterName).isEmpty() ? "HAHAHA" : response.data().getCounter().counterName;
TextView Name = (TextView) findViewById(R.id.counterName);
Name.setText(nameStr);
}
}
});
}
#Override
public void onFailure(#Nonnull ApolloException e) {
}
};

Related

Display and hide progress bar using MVVM pattern

I am working with MVVM pattern. I have just started it and i have done it successfully.
But I don't understand how to add progress bar for showing and hide as we normally do for API calls.
I am not using data binding. So how can i use progress bar for showing and hide it.
For Login
public class LoginRepository {
private DATAModel dataModel = new DATAModel();
private MutableLiveData<DATAModel> mutableLiveData = new MutableLiveData<>();
private Application application;
public LoginRepository(Application application) {
this.application = application;
}
public MutableLiveData<DATAModel> getMutableLiveData(String username, String password) {
APIRequest apiRequest = RetrofitRequest.getRetrofit().create(APIRequest.class);
JsonLogin jsonLogin = new JsonLogin(Constants.DEVICE_TYPE, Functions.getDeviceId(application.getApplicationContext()), Constants.APP_VERSION, Constants.API_VERSION, Functions.getTimeStamp(), Functions.getDeviceModel(), Build.VERSION.RELEASE, username, password);
Call<APIResponseLogin> call = apiRequest.getUsersDetails(jsonLogin);
call.enqueue(new Callback<APIResponseLogin>() {
#Override
public void onResponse(Call<APIResponseLogin> call, Response<APIResponseLogin> response) {
APIResponseLogin apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatuscode() == 0) {
if (apiResponse.getDataModel() != null) {
dataModel = apiResponse.getDataModel();
mutableLiveData.setValue(dataModel);
}
} else if (apiResponse != null && apiResponse.getStatuscode() == 1) {
Log.v("AAAAAAAAA", apiResponse.getStatusmessage());
}
}
#Override
public void onFailure(Call<APIResponseLogin> call, Throwable t) {
Log.v("ErrorResponse", t.getMessage() + " : " + call.request().toString());
}
});
return mutableLiveData;
}
Activity Code
void loginCall() {
loginViewModel.getUserDetails(editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim()).observe(this, new Observer<DATAModel>() {
#Override
public void onChanged(#Nullable DATAModel dataModel) {
if (dataModel != null) {
Userdetails userdetails = dataModel.getUserdetails();
List<ContactTypes> contactTypes = dataModel.getContactTypes();
if (userdetails != null) {
MySharedPreferences.setCustomPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USERDETAILS, userdetails);
MySharedPreferences.setStringPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USER_ID, userdetails.getUserId());
}
if (contactTypes != null) {
MySharedPreferences.setCustomArrayList(LoginActivity.this, Constants.SHAREDPREFERENCE_CONTACTTYPES, contactTypes);
}
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
}
Advanced help would be appreciated!
When you call api that time you have to take one live variable which shows your api is in loading mode or not and after success or failure you have to update that variable.
After observe that variable in your activity or fragment class and show or hide your progress.
public class LoginRepository {
private DATAModel dataModel = new DATAModel();
private MutableLiveData<DATAModel> mutableLiveData = new MutableLiveData<>();
private Application application;
private MutableLiveData<Boolean> progressbarObservable;
public LoginRepository(Application application) {
this.application = application;
}
public MutableLiveData<DATAModel> getMutableLiveData(String username, String password) {
// add below line
progressbarObservable.value = true
APIRequest apiRequest = RetrofitRequest.getRetrofit().create(APIRequest.class);
JsonLogin jsonLogin = new JsonLogin(Constants.DEVICE_TYPE, Functions.getDeviceId(application.getApplicationContext()), Constants.APP_VERSION, Constants.API_VERSION, Functions.getTimeStamp(), Functions.getDeviceModel(), Build.VERSION.RELEASE, username, password);
Call<APIResponseLogin> call = apiRequest.getUsersDetails(jsonLogin);
call.enqueue(new Callback<APIResponseLogin>() {
#Override
public void onResponse(Call<APIResponseLogin> call, Response<APIResponseLogin> response) {
// add below line
progressbarObservable.value = false
APIResponseLogin apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatuscode() == 0) {
if (apiResponse.getDataModel() != null) {
dataModel = apiResponse.getDataModel();
mutableLiveData.setValue(dataModel);
}
} else if (apiResponse != null && apiResponse.getStatuscode() == 1) {
Log.v("AAAAAAAAA", apiResponse.getStatusmessage());
}
}
#Override
public void onFailure(Call<APIResponseLogin> call, Throwable t) {
// add below line
progressbarObservable.value = false
Log.v("ErrorResponse", t.getMessage() + " : " + call.request().toString());
}
});
return mutableLiveData;
}
}
Now, observe above variable in activity or fragment and based on that value hide or show your progress bar
public class LoginActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
observeLogin();
}
#Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.button_login:
// Do something
loginCall();
}
}
private void observeLogin() {
loginViewModel.progressbarObservable().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(final Boolean progressObserve) {
if(progressObserve){
show your progress
}
else {
hide your progress
}
}
});
}
void loginCall() {
loginViewModel.getUserDetails(editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim()).observe(this, new Observer<DATAModel>() {
#Override
public void onChanged(#Nullable DATAModel dataModel) {
if (dataModel != null) {
Userdetails userdetails = dataModel.getUserdetails();
List<ContactTypes> contactTypes = dataModel.getContactTypes();
if (userdetails != null) {
MySharedPreferences.setCustomPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USERDETAILS, userdetails);
MySharedPreferences.setStringPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USER_ID, userdetails.getUserId());
}
if (contactTypes != null) {
MySharedPreferences.setCustomArrayList(LoginActivity.this, Constants.SHAREDPREFERENCE_CONTACTTYPES, contactTypes);
}
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
}
}
I find it easier to write my own callback interface in this situation. Just not that this will be done synchronously so all will wait until your api call responds. But in such a case, a progress dialog would be havin the similar effect.
1.Create inteface:
public interface ProgressCallback{
void onDone(String message);
void onFail(String message);
}
Now in your method where you call the API
loginUser(String name, String password, ProgressCallback
progressCallback){
call.enqueue(new Callback<LoginData>() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onResponse(Call<LoginData> call, Response<LoginData> response) {
progressCallBack.onSuccess(response.message());
}
#Override
public void onFailure(Call<LoginData> call, Throwable t) {
progressCallBack.onFail(t.getMessage());
}
});
Now when you call the method
loginUser("John#doe.com", "applesgravity", new ProgressCallBack() {
#Override
public void onSuccess(String message) {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onFail(String message) {
progressBar.setVisibility(View.INVISIBLE);
}
});

Android custom listner callback to a different place

I have a general custom listener/callback question.
In my code, I have the following interface and LocalDB class that read room database:
# Custom interface
public interface MyInterface {
void OnSuccess();
void OnFailure();
}
# Class LocalDB
public class LocalDB {
private MyInterface myInterface;
public static PIMUserLocalDataSource getInstance(#NonNull Context context)
{
if (INSTANCE == null) {
synchronized (PIMUserLocalDataSource.class) {
INSTANCE = new PIMUserLocalDataSource(context);
}
}
return INSTANCE;
}
public void setCustomListener(CustomListener customListener) {
this.customListener = customListener;
}
private void queryA() {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryA();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
private void queryB() {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryB();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
}
# Fragment / Activity
LocalDB myDB = LocalDB.getInstance(context)
myDB.setCustomListener(new CustomListener) {
#Override
public void OnSuccess() {
Log.e(logTag, "Success queryA");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryA");
}
}
myDB.queryA()
myDB.setCustomListener(new CustomListener) {
#Override
public void OnSuccess() {
Log.e(logTag, "Success queryB");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryB");
}
}
myDB.queryB()
Problem
These works fine most of the time, however, there is sometimes that queryA is slow and queryB is done before queryA, queryB callback to queryB no problem, but when queryA is done, it callback to queryB listener. I think because the listener of B overwritten A? How should I avoid this kind of problem?
when you call queryA or queryB. pass the listener.
# Custom interface
public interface MyInterface {
void OnSuccess();
void OnFailure();
}
# Class LocalDB
public class LocalDB {
boolean successA,successB;
public static PIMUserLocalDataSource getInstance(#NonNull Context context)
{
if (INSTANCE == null) {
synchronized (PIMUserLocalDataSource.class) {
INSTANCE = new PIMUserLocalDataSource(context);
}
}
return INSTANCE;
}
private void queryA(CustomListener customListener) {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryA();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
private void queryB(CustomListener customListener) {
Runnable runnable = new Runnable() {
result = appDatabase.myDao().getQueryB();
if (result != null) {
if (customListener != null) {
customListener.onSuccess();
} else {
customListener.onFailure();
}
}
}
}
}
# Fragment / Activity
LocalDB myDB_A = LocalDB.getInstance(context)
myDB.setCustomListener(new CustomListener) {
#Override
public void OnSuccess() {
successA=true;
checkIfTwoFinishedExcutecode();
Log.e(logTag, "Success queryA");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryA");
}
}
myDB.queryA(myDB_A )
LocalDB myDB_B = LocalDB.getInstance(context)
#Override
public void OnSuccess() {
successB=true;
checkIfTwoFinishedExcutecode();
Log.e(logTag, "Success queryB");
}
#Override
public void OnFailure() {
Log.e(logTag, "Failed queryB");
}
}
myDB.queryB(myDB_B)
void checkIfTwoFinishedExcutecode(){
if(successA&&successB){
// the two is finished. write your code
}
}

Solved: Android socket is not getting connected to the server

Here I have a query related to connection between android socket and server. I'm following https://socket.io/blog/native-socket-io-and-android/ and found that it is working fine, so I replaced my local server URL with the URL in the tutorial. But here I'm always getting a connection failed or disconnection error. Here is my application class for further clarification.
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
IO.Options options = new IO.Options();
options.forceNew = true;
options.reconnection = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("uid", 1);
jsonObject.put("usid", 6847);
options.query = jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("JSON", jsonObject.toString());
Log.e("OPTIONS", options.toString());
mSocket = IO.socket(Constants.CHAT_SERVER_URL, options);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
And the code of the fragment is below. It keeps calling onDisconnect() whenever I use my local server for it.
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private static final int REQUEST_LOGIN = 0;
private static final int TYPING_TIMER_LENGTH = 600;
private RecyclerView mMessagesView;
private EditText mInputMessageView;
private List<Message> mMessages = new ArrayList<Message>();
private RecyclerView.Adapter mAdapter;
private boolean mTyping = false;
private Handler mTypingHandler = new Handler();
private String mUsername;
private Socket mSocket;
private Boolean isConnected = true;
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isConnected) {
if (null != mUsername)
mSocket.emit("add user", mUsername);
Toast.makeText(getActivity().getApplicationContext(),
R.string.connect, Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "diconnected");
isConnected = false;
Toast.makeText(getActivity().getApplicationContext(),
R.string.disconnect, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error connecting");
Toast.makeText(getActivity().getApplicationContext(),
R.string.error_connect, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
removeTyping(username);
addMessage(username, message);
}
});
}
};
private Emitter.Listener onUserJoined = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
int numUsers;
try {
username = data.getString("username");
numUsers = data.getInt("numUsers");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addLog(getResources().getString(R.string.message_user_joined, username));
addParticipantsLog(numUsers);
}
});
}
};
private Emitter.Listener onUserLeft = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
int numUsers;
try {
username = data.getString("username");
numUsers = data.getInt("numUsers");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addLog(getResources().getString(R.string.message_user_left, username));
addParticipantsLog(numUsers);
removeTyping(username);
}
});
}
};
private Emitter.Listener onTyping = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
try {
username = data.getString("username");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addTyping(username);
}
});
}
};
private Emitter.Listener onStopTyping = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
try {
username = data.getString("username");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
removeTyping(username);
}
});
}
};
private Runnable onTypingTimeout = new Runnable() {
#Override
public void run() {
if (!mTyping) return;
mTyping = false;
mSocket.emit("stop typing");
}
};
public MainFragment() {
super();
}
// This event fires 1st, before creation of fragment or any views
// The onAttach method is called when the Fragment instance is associated with an Activity.
// This does not mean the Activity is fully initialized.
#Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new MessageAdapter(context, mMessages);
if (context instanceof Activity) {
//this.listener = (MainActivity) context;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ChatApplication app = (ChatApplication) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("new message", onNewMessage);
mSocket.on("user joined", onUserJoined);
mSocket.on("user left", onUserLeft);
mSocket.on("typing", onTyping);
mSocket.on("stop typing", onStopTyping);
mSocket.connect();
startSignIn();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("new message", onNewMessage);
mSocket.off("user joined", onUserJoined);
mSocket.off("user left", onUserLeft);
mSocket.off("typing", onTyping);
mSocket.off("stop typing", onStopTyping);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMessagesView = (RecyclerView) view.findViewById(R.id.messages);
mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesView.setAdapter(mAdapter);
mInputMessageView = (EditText) view.findViewById(R.id.message_input);
mInputMessageView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int id, KeyEvent event) {
if (id == R.id.send || id == EditorInfo.IME_NULL) {
attemptSend();
return true;
}
return false;
}
});
mInputMessageView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (null == mUsername) return;
if (!mSocket.connected()) return;
if (!mTyping) {
mTyping = true;
mSocket.emit("typing");
}
mTypingHandler.removeCallbacks(onTypingTimeout);
mTypingHandler.postDelayed(onTypingTimeout, TYPING_TIMER_LENGTH);
}
#Override
public void afterTextChanged(Editable s) {
}
});
ImageButton sendButton = (ImageButton) view.findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attemptSend();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK != resultCode) {
getActivity().finish();
return;
}
mUsername = data.getStringExtra("username");
int numUsers = data.getIntExtra("numUsers", 1);
addLog(getResources().getString(R.string.message_welcome));
addParticipantsLog(numUsers);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
}
#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_leave) {
leave();
return true;
}
return super.onOptionsItemSelected(item);
}
private void addLog(String message) {
mMessages.add(new Message.Builder(Message.TYPE_LOG)
.message(message).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void addParticipantsLog(int numUsers) {
addLog(getResources().getQuantityString(R.plurals.message_participants, numUsers, numUsers));
}
private void addMessage(String username, String message) {
mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
.username(username).message(message).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void addTyping(String username) {
mMessages.add(new Message.Builder(Message.TYPE_ACTION)
.username(username).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void removeTyping(String username) {
for (int i = mMessages.size() - 1; i >= 0; i--) {
Message message = mMessages.get(i);
if (message.getType() == Message.TYPE_ACTION && message.getUsername().equals(username)) {
mMessages.remove(i);
mAdapter.notifyItemRemoved(i);
}
}
}
private void attemptSend() {
if (null == mUsername) return;
if (!mSocket.connected()) return;
mTyping = false;
String message = mInputMessageView.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
mInputMessageView.requestFocus();
return;
}
mInputMessageView.setText("");
addMessage(mUsername, message);
// perform the sending message attempt.
mSocket.emit("new message", message);
}
private void startSignIn() {
// mUsername = null;
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivityForResult(intent, REQUEST_LOGIN);
}
private void leave() {
mUsername = null;
mSocket.disconnect();
mSocket.connect();
startSignIn();
}
private void scrollToBottom() {
mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
}
}
I'm using CHAT_SERVER_URL = "http://192.168.1.14:3000/" to make connection with server but it's not working for me. It works fine when we try to make a web connection through emulator or computer system. Can anyone please give me an idea if I'm doing anything wrong.
Thanks.
After debugging at the server end too, I got to know how to hit my server to make a connection and I got that we don't require IO.Options and Options.query in every case and now it is working fine completely. So for more clarification I'm posting an answer here:
//connect to server
public void startRunning() {
try {
if (baseUrl != null) {
socket = IO.socket("http://" + baseUrl + ":3000?uid=" + userId + "&usid=" + userSessionId);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (socket == null) return;
socket
.on(Socket.EVENT_CONNECT, CONNECTED)
.on(Socket.EVENT_DISCONNECT, DISCONNECTED)
.on("chat-message", CHAT_MESSAGE)
.on("chats-active", CHATS_ACTIVE)
.on("chat-logout", LOGOUT)
.on("messages-read", MESSAGE_READ)
.on("chat-login", CHAT_LOGIN);
socket.connect();
}

App crashes after few seconds [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am working on an app which dosen't show me any errors and runs just fine, but after a second just crashes, I tried everything but could not find the error (being new) can someone please tell me where am I doing wrong as
logcat
11-08 12:57:16.011 5886-5886/com.koshur.socialnetwork E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.koshur.socialnetwork, PID: 5886
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.koshur.socialnetwork.adapters.HomeListAdapter.setPosts(java.util.List)' on a null object reference
at com.koshur.socialnetwork.activities.ProfilePreview.updateView(ProfilePreview.java:334)
at com.koshur.socialnetwork.activities.ProfilePreview.access$300(ProfilePreview.java:42)
at com.koshur.socialnetwork.activities.ProfilePreview$5.success(ProfilePreview.java:308)
at com.koshur.socialnetwork.activities.ProfilePreview$5.success(ProfilePreview.java:300)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
java class
public class ProfilePreview extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
public TextView userProfileName,
userTotalFollowers,
userTotalPosts,
userProfileAddress,
userProfileJob,
followProfileBtn,
contactProfileBtn,
userPostsBtn;
public userItem user;
public RecyclerView postsList;
public LinearLayoutManager layoutManager;
int currentPage = 1;
private HomeListAdapter mHomeListAdapter;
private SwipeRefreshLayout mSwipeRefreshLayout;
public ImageView userProfilePicture, userProfileCover;
public LinearLayout actionProfileArea;
public int userID = 0;
private CacheManager mCacheManager;
private ThinDownloadManager downloadManager;
private Gson mGson;
LoadingView loginLoadingView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
setContentView(R.layout.activity_profile_preview);
initializeView();
loginLoadingView = (LoadingView)findViewById(R.id.loginLoadingView);
if (getIntent().hasExtra("userID")) {
userID = getIntent().getExtras().getInt("userID");
}
mCacheManager = CacheManager.getInstance(getApplicationContext());
mGson = new Gson();
getUser();
getPosts();
}
}
private void initializeView() {
downloadManager = new ThinDownloadManager(AppConst.DOWNLOAD_THREAD_POOL_SIZE);
userProfileName = (TextView) findViewById(R.id.userProfileName);
userProfilePicture = (ImageView) findViewById(R.id.userProfilePicture);
userTotalFollowers = (TextView) findViewById(R.id.userTotalFollowers);
userTotalPosts = (TextView) findViewById(R.id.userTotalPosts);
followProfileBtn = (TextView) findViewById(R.id.followProfileBtn);
contactProfileBtn = (TextView) findViewById(R.id.contactProfileBtn);
actionProfileArea = (LinearLayout) findViewById(R.id.actionProfileArea);
userProfileAddress = (TextView) findViewById(R.id.userProfileAddress);
userProfileJob = (TextView) findViewById(R.id.userProfileJob);
userProfileCover = (ImageView) findViewById(R.id.userProfileCover);
userPostsBtn = (TextView) findViewById(R.id.userPostsBtn);
userPostsBtn.setOnClickListener(this);
followProfileBtn.setOnClickListener(this);
contactProfileBtn.setOnClickListener(this);
postsList = (RecyclerView) findViewById(R.id.postsList);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeHome);
mSwipeRefreshLayout.setOnRefreshListener(this);
postsList.setOnScrollListener(new HidingScrollListener(layoutManager) {
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onLoadMore(int currentPage) {
setCurrentPage(currentPage);
getPosts();
}
});
}
private void getUser() {
if (M.isNetworkAvailable(getApplicationContext())) {
loginLoadingView.setLoading(true);
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(userID, new Callback<userItem>() {
#Override
public void success(userItem user, retrofit.client.Response response) {
try {
mCacheManager.write(mGson.toJson(user), "Profile-" + userID + ".json");
} catch (Exception e) {
e.printStackTrace();
}
updateView(user);
}
#Override
public void failure(RetrofitError error) {
loginLoadingView.setLoading(false);
M.T(ProfilePreview.this, getString(R.string.ServerError));
}
});
} else {
try {
String profile = mCacheManager.readString("Profile-" + userID + ".json");
Gson mGson = new Gson();
updateView((userItem) mGson.fromJson(profile, new TypeToken<userItem>() {
}.getType()));
} catch (Exception e) {
M.L(e.getMessage());
}
}
}
private void downloadFile(String url, String hash) {
if (getFilePath(hash) == null) {
Uri downloadUri = Uri.parse(url);
Uri destinationUri = Uri.parse(M.getFilePath(getApplicationContext(), hash));
DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setDestinationURI(destinationUri);
downloadManager.add(downloadRequest);
}
}
private void updateView(userItem user) {
this.user = user;
if (user.isMine()) {
actionProfileArea.setVisibility(View.GONE);
} else {
actionProfileArea.setVisibility(View.VISIBLE);
}
if (user.isFollowed()) {
followProfileBtn.setText(getString(R.string.UnFollow));
contactProfileBtn.setVisibility(View.VISIBLE);
} else {
followProfileBtn.setText(getString(R.string.Follow));
contactProfileBtn.setVisibility(View.GONE);
}
if (user.getName() != null) {
userProfileName.setText(user.getName());
} else {
userProfileName.setText(user.getUsername());
}
if (user.getAddress() != null) {
userProfileAddress.setVisibility(View.VISIBLE);
userProfileAddress.setText(user.getAddress());
} else {
userProfileAddress.setVisibility(View.GONE);
}
if (user.getJob() != null) {
userProfileJob.setVisibility(View.VISIBLE);
userProfileJob.setText(user.getJob());
} else {
userProfileJob.setVisibility(View.GONE);
}
if (getFilePath(user.getPicture()) != null) {
Picasso.with(this)
.load(new File(getFilePath(user.getPicture())))
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(userProfilePicture);
} else {
Picasso.with(this)
.load(AppConst.IMAGE_PROFILE_URL + user.getPicture())
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(userProfilePicture);
downloadFile(AppConst.IMAGE_PROFILE_URL + user.getPicture(), user.getPicture());
}
if (user.getCover() != null) {
if (getFilePath(user.getCover()) != null) {
userProfileCover.setImageURI(Uri.parse(getFilePath(user.getCover())));
} else {
Picasso.with(this)
.load(AppConst.IMAGE_COVER_URL + user.getCover())
.placeholder(R.drawable.header)
.error(R.drawable.header)
.into(userProfileCover);
downloadFile(AppConst.IMAGE_COVER_URL + user.getCover(), user.getCover());
}
} else {
Picasso.with(this)
.load(R.drawable.header)
.into(userProfileCover);
}
userTotalFollowers.setText(user.getTotalFollowers() + "");
userTotalPosts.setText(user.getTotalPosts() + "");
loginLoadingView.setLoading(false);
}
private String getFilePath(String hash) {
return M.filePath(getApplicationContext(), hash);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.followProfileBtn:
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.followToggle(userID, new Callback<ResponseModel>() {
#Override
public void success(ResponseModel responseModel, Response response) {
if (responseModel.isDone()) {
if (user.isFollowed()) {
user.setFollowed(false);
followProfileBtn.setText(getString(R.string.Follow));
loginLoadingView.setLoading(true);
contactProfileBtn.setVisibility(View.GONE);
loginLoadingView.setLoading(false);
} else {
user.setFollowed(true);
followProfileBtn.setText(getString(R.string.UnFollow));
contactProfileBtn.setVisibility(View.VISIBLE);
}
} else {
M.T(ProfilePreview.this, responseModel.getMessage());
}
}
#Override
public void failure(RetrofitError error) {
M.T(ProfilePreview.this, getString(R.string.ServerError));
}
});
break;
case R.id.contactProfileBtn:
Intent messagingIntent = new Intent(this, MessagingActivity.class);
messagingIntent.putExtra("conversationID", 0);
messagingIntent.putExtra("recipientID", userID);
startActivity(messagingIntent);
break;
case R.id.userPostsBtn:
Intent userPostsIntent = new Intent(this, UserPosts.class);
userPostsIntent.putExtra("userID", userID);
startActivity(userPostsIntent);
finish();
break;
}
}
public void getPosts() {
if (M.isNetworkAvailable(this)) {
if (!mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(true);
}
PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(this));
mPostsAPI.getUserPosts(userID, getCurrentPage(), new Callback<List<PostsItem>>() {
#Override
public void success(List<PostsItem> postsItems, retrofit.client.Response response) {
try {
mCacheManager.write(mGson.toJson(postsItems), "UserPosts-" + userID + ".json");
} catch (Exception e) {
e.printStackTrace();
}
updateView(postsItems);
}
#Override
public void failure(RetrofitError error) {
loginLoadingView.setLoading(false);
}
});
} else {
try {
String UserPostsString = mCacheManager.readString("UserPosts-" + userID + ".json");
updateView((List<PostsItem>) mGson.fromJson(UserPostsString, new TypeToken<List<PostsItem>>() {
}.getType()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateView(List<PostsItem> postsItems) {
if (getCurrentPage() != 1) {
List<PostsItem> oldItems = mHomeListAdapter.getPosts();
oldItems.addAll(postsItems);
mHomeListAdapter.setPosts(oldItems);
} else {
mHomeListAdapter.setPosts(postsItems);
}
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void onRefresh() {
setCurrentPage(1);
getPosts();
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
At least from the code you posted you are not initialising your mhomelistadapter so it is null when you call setPosts

How to fix "android.view.ViewRootImpl$CalledFromWrongThreadException"

I want to fix error as follows:
"android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."
here are my code.
public class MainActivity extends Activity {
#SuppressLint("NewApi") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
onShowMessage();
}
public void removeContent() {
LinearLayout list = (LinearLayout) findViewById(R.id.linearlayout_list);
list.removeAllViews();
}
public void onShowMessage() {
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
String id = "id1";
String message = "message1";
String response = HTTPUtils.HTTPPost(Global.MESSAGE_URL,
"id", id,
"message", message);
process(response);
}
});
myThread.start();
}
private void process(String response) {
if (response == null || response.equals("")) {
return;
} else {
try {
JSONObject json = null;
try {
json = FbUtil.parseJson(response);
} catch (FacebookError e) {
showErrorMessage();
}
if (json.has("exception")) {
showErrorMessage();
return;
} else {
Global.list = JsonParser.getInfo(json);
removeContent();
initView();
return;
}
} catch (JSONException e) {
}
return;
}
}
}
error occur on removeContent();
please help me.
You are updating Views in a different thread
removeContent();
initView();
Call this two methods in a UI thread like.
runOnUiThread(new Runnable() {
#Override
public void run() {
removeContent();
initView();
}
});

Categories

Resources