This is the only Place my app crashes and one of the more important features
The LogCat tells me:
java.lang.IllegalArgumentException: You must create this type of ParseObject using ParseObject.create() or the proper subclass.
at line 37.
I tried the ParseObject.create() however that just caused more problems (I may have done it incorrectly). How Should I code this?
Here is my newPost class:
public class newPost extends Activity {
private Button addButton;
private TextView postView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newpost);
postView = ((EditText) findViewById(R.id.postView));
addButton = ((Button) findViewById(R.id.addButton));
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//line 37 Below
ParseObject post = new ParseObject("Posts");
post.put("content", postView);
post.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException e) {
if (e == null) {
setResult(RESULT_OK);
finish();
} else {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}
});
}
});
}
Replace this line
ParseObject post = new ParseObject("Posts");
with this
ParseObject post = ParseObject.create("Posts");
Ensure that you've added the below line in the Application.java class where Parse is initialised
ParseObject.registerSubclass(Message.class);
In my case I had to remove the '#ParseClassName' annotation in my model class. My understanding is that if I have a parse model class 'Posts' and I call 'registerSubclass(yourclassname)' in Application, then all I need is
Post obj = new Post();
You probably made a mistake in initialising Parse in your Application class. Or forgot to put android:name=".YourApplicationClass" in your Manifest file.
I got this error because I forgot to register my parse class as a subclass in my application extension:
public class App extends Application
{
#Override
public void onCreate()
{
super.onCreate();
App application = this;
ParseObject.registerSubclass(Posts.class); // <-- This is what you need
Parse.enableLocalDatastore(this);
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(EnvironmentConfig.appID)
.server(EnvironmentConfig.serverName)
.enableLocalDataStore()
.build());
ParseInstallation.getCurrentInstallation().saveInBackground();
}
}
Related
I'm a beginner learning Android.
I'm trying to make my application receive data from local database.
So I used retroit2 as followed
public class SNSDataServicer {
private String BASE_URL = "http://10.0.2.2:8080/";
Retrofit retrofitClient =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
SelectAPI select = retrofitClient.create(SelectAPI.class);
InsertAPI insert = retrofitClient.create(InsertAPI.class);
UpdateAPI update = retrofitClient.create(UpdateAPI.class);
DeleteAPI delete = retrofitClient.create(DeleteAPI.class);
}
interface SelectAPI{
#GET("sns/all/{candidate}")
Call<List<SNSData>> selectAllByCandidate(#Path("candidate") String candidate);
}
and this is the code for MainActivity.java
public class MainActivity extends AppCompatActivity {
SNSDataServicer dataService = new SNSDataServicer();
List<SNSData> snsDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView checker = findViewById(R.id.checker);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dataService.select.selectAllByCandidate("3").enqueue(new Callback<List<SNSData>>() {
#Override
public void onResponse(Call<List<SNSData>> call, Response<List<SNSData>> response) {
snsDataList = response.body();
return;
}
#Override
public void onFailure(Call<List<SNSData>> call, Throwable t) {
t.printStackTrace();
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
Log.d("Failure", "onResponse: Failed");
}
});
if(snsDataList==null) {
checker.setText("null");
} else {
checker.setText(snsDataList.get(0).getMedia());
}
}
});
}
}
When I press button, the textview's text should be set to size of the list.
But snsDataList kept on returning null
eventhough reponse.body() returned list successfully
below is scree capture of my debugging.
1.
enter image description here
by this point it was perfect, but when I hit F8 to debug next step
enter image description here
response body has been changed and when I hit F8 more, it takes me to
ExecutorCallAdapterFactory.java
Handler.class
Looper.class
and no more.
Then suddenly my snsDataList becomes null...
This is ridiculously hard for me and I've tried to solve it by myself for very long but I have failed...
Can someone help me with this problem? It will be really grateful.
I'm getting a null point exception in Android studio. I'm trying to integrate Helpshift into my current app. The null point is being called on the help button I think. The error I'm getting is:
java.lang.NullPointerException: Attempt to invoke interface method
'void com.helpshift.CoreApi.updateApiConfig(java.util.Map)' on a null object reference
My code looks like
package com.example.leoconnelly.connexus;
public class MainActivity extends AppCompatActivity {
ImageButton FindCareButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//THE PURPLE BUTTON!!!!!!!
FindCareButton = (findViewById(R.id.find_care_button));
FindCareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openFindCare();
}
});
/*
GetStartedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openSearchActivity();
}
});
*/
ImageButton helpButton = (ImageButton) findViewById(R.id.imageButton13);
helpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ApiConfig.Builder configBuilder = new ApiConfig.Builder();
configBuilder.setRequireEmail(true);
configBuilder.setEnableTypingIndicator(true);
com.helpshift.support.Support.showConversation(MainActivity.this, configBuilder.build() );
}
});
}
public void openFindCare () {
Intent mainActivityToFindCare = new Intent (this,
HealthCenterListActivity.class);
startActivity(mainActivityToFindCare);
}
}
I'm not exactly sure what it's pointing too. I'm trying to open FAQs from Helpshift.
You are missing the InstallConfig for the API. Try adding it in the Calling Activity.
import com.helpshift.Core;
import com.helpshift.All;
import com.helpshift.InstallConfig;
import com.helpshift.exceptions.InstallException;
Core.init(All.getInstance());
InstallConfig installConfig = new InstallConfig.Builder()
.setEnableInAppNotification(true)
.build();
try {
Core.install(getApplication(),
API_KEY,
DOMAIN,
APP_ID, installConfig);
} catch (InstallException e) {
android.util.Log.e("Helpshift", "install call : ", e);
}
Below is a login activity which connects with the server to perform login operation, so for this to do in Background thread how to use Asynctask's methods correctly?
I am new to android and not used Asynctask before, but I have seen tutorials still couldn't do it myself
//public class LoginActivity extends AppCompatActivity extends Asynctask shows some error
Edit: error is here
//public class LoginActivity extends AsyncTask extends
AppCompatActivity{ ( { expected)
public class LoginActivity extends AppCompatActivity{
private TextView tvLFS, tvOr;
private Button btnLog;
private EditText etUn, etPw;
private static final String TAG = "LoginActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//remove action bar
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
//change font of the heading
tvLFS = (TextView) findViewById(R.id.tvHeadingLFS);
Typeface typeface =
Typeface.createFromAsset(getAssets(),
"fonts/futuramediumitalicbt.ttf");
tvLFS.setTypeface(typeface);
init();
}
private void init() {
tvLFS = (TextView) findViewById(R.id.tvHeadingLFS);
tvOr = (TextView) findViewById(R.id.tvOR_LOGIN_USING);
btnLog = (Button) findViewById(R.id.btnLogin);
etUn = (EditText) findViewById(R.id.etUName);
etPw = (EditText) findViewById(R.id.etPass);
/* SharedPreferences pref = getSharedPreferences("ActivityPREF",
Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putBoolean("activity_executed", true);
edt.commit();*/
btnLog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
final String usname = etUn.getText().toString();
final String uspass = etPw.getText().toString();
final LoginRequest loginRequest = new LoginRequest();
loginRequest.setClientType("mobile");
loginRequest.setMsService("login");
loginRequest.setMsServiceType("user-management");
List<LoginRequest.MsDataLogin> msDataLogList = new
ArrayList<>();
LoginRequest.MsDataLogin msData =
loginRequest.getMsDAtaLoginInstance();
msData.setUserName(usname);
msData.setUserPass(uspass);
msDataLogList.add(msData);
loginRequest.setMsData(msDataLogList);
RestClient.getApiInterface().postData(loginRequest).enqueue(new
ResponseResolver<LoginResponse>(LoginActivity.this) {
#Override
public void success(LoginResponse loginResponse) {
if (loginResponse.getErrorCode().equals("0"))
{
Toast.makeText(LoginActivity.this,
"Logged-in successfully!!", Toast.LENGTH_SHORT).show();
Intent in = new
Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
finish();
} else
if(loginResponse.getErrorCode().equals("1")){
Toast.makeText(LoginActivity.this, "No
account found!! Please register", Toast.LENGTH_LONG).show();
}
}
#Override
public void failure(APIError error) {
Log.d(TAG, "failure: error--
"+error.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Based on you edit, you're trying to extend two classes? Well, (I think) that's not possible in Java ...
Back to your question about AsyncTask. AsynTask are made to make task outside de Main Thread/UI Thread, for some scenarios (Ex.: the basic, not lock the UI while doing some work), for that reason you can't interact with the UI in a AsyncTask or even mix both things (is possible in some cases, but not recommended).
So you need to extends AsyncTask in other class than your view/activity (another Class.java or nested/internal class), example below:
public class MyAsyncTask extends AsyncTask<ParameterType, ProgressType, ReturnType> {
//Example to demonstrate UI interation
private IView view;
public MyAsyncTask(IView view) {
this.view = view;
}
#Override
protected ReturnType doInBackground(ParameterType... params) {
// do and update the work
return new ReturnType(); // work is done, return the result
}
// Override this method if you need to do something after the AsyncTask has finished (based on the return). Here you can interact with the UI too.
#Override
protected void onPostExecute(ReturnType o) {
// Example of UI interaction
view.updateUI(o);
}
}
If you don't need Parameters, Returns or update the progress of your AsyncTask, you can use the 'Void' type in place ParameterType, ProgressType or ReturnType.
Then you can create a intance of MyAsyncTask in other classes (Ex.: your activity) an call ‘execute()’ method to start the AsyncTask.
public class Foobar extends AppCompatActivity implements IView {
... code ...
MyAsyncTask fooTask = new MyAsyncTask(this); // Foobar class needs to implement IView interface
fooTask.execute(parameters); // execute AsyncTask with 'parameters'
... code ...
}
Based on your code you're trying to make a Network call. So you need need migrate your network call to inside 'doInBackground' method, and call the next activity (or show the error) in the 'onPostExecute'.
I not very familiar with your implementation (RestClient, ResponseResolver), but I think you can use Retrofit/Jackson libraries for a more solid solution. They are not very difficult to understand and makes Network calls easier.
In the references below there are other alternatives that you can use instead of a AsyncTask.
Here is some references:
https://developer.android.com/reference/android/os/AsyncTask.html
https://developer.android.com/guide/components/processes-and-threads.html
Good coding.
I want to fetch JSON string array from server using Retrofit.
The JSON array is like this.
["A","B","C"]
Here is the code I made .
MainActivity.class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url="http://proverbs-app.antjan.us";
RestAdapter restAdapter;
restAdapter = new RestAdapter.Builder()
.setEndpoint(url)
.build();
Service service=restAdapter.create(Service.class);
service.get(new Callback<List<String>>(){
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
#Override
public void success(List<String> arg0, Response arg1) {
Toast.makeText(getApplicationContext(), arg0.toString(), Toast.LENGTH_LONG).show();
}
});
}
}
Here is the Service.class
public interface Service {
#GET("/")
public void get(Callback<List<String>> callback);
}
It shows only "Error" Toast.
Am I something wrong with my codes.
Please help me to fix it.
I'm a beginner.
So,please answer me in detail because I don't know much about it.
Thanks in advance.
You need to specify relative path for URL in the interface.
#GET("/")
public void get(Callback<List<String>> callback);
It looks like you're missing Gson. Add this line to your dependencies block in build.gradle:
compile 'com.google.code.gson:gson:2.3.1'
I have problem with my App ,, and want to solve it but i could not access to solution please help me ,,,
// Main_Activity Class
public class MainActivity extends Activity {
Button Open_play_list;
AccessPlayList accessPL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Open_play_list = (Button)findViewById(R.id.btnShA);
accessPL = new AccessPlayList();
Open_play_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Calling method tht contain code for open playlist
try {
accessPL.openPlaylist();
}`enter code here`
catch (Exception ex) {
Toast.makeText(getBaseContext(), ex.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
});
}
// AccessPlayList Class
public class AccessPlayList extends Activity {
Intent intentPL;
int REQUEST_CODE = 1;
int PLAYLIST_ID = 2;
public void openPlaylist()
{
intentPL = new Intent(Intent.ACTION_PICK);
intentPL.setComponent(new ComponentName("com.android.music","com.android.music.PlaylistBrowserActivity"));
intentPL.setType("MediaStore.Audio.Playlist.CONTENT_TYPE");
intentPL.setFlags(0x10000000);
intentPL.putExtra("oneShot",false);
intentPL.putExtra("PlayList",PLAYLIST_ID);
startActivityForResult(intentPL,REQUEST_CODE);
}
}
Since you did not post which line of your code is where the error is occurring, the only thing I can tell you is that you need to check if the object causing the problem is null.
Try some validation like this:
if(object != null){
//do something
}