Error uploading file to server Java - java

I am trying to create an application that sends a file to a server. The application consists of one button that when clicked, will upload a file to a server. Here is the code that I have so far:
public class MainActivity extends Activity implements OnClickListener {
final String TAG = "sendButton";
final String TAG2 = "messageButton";
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
String result = null;
String url = "http://192.168.1.18";
File file = new File("example.txt");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// findViewById(R.id.button2).setOnClickListener(this);
//findViewById(R.id.button2).setOnClickListener(this);
setupsendMessage();
//setupmessageButton();
uploadButton = (Button)findViewById(R.id.button1);
messageText = (TextView)findViewById(R.id.button2);
}
private void setupsendMessage() {
// do something when the button is pressed
//
Button sendButton = (Button) findViewById(R.id.button1);
sendButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(file);
builder.addPart("file", fileBody);
final HttpEntity yourEntity = builder.build();
post.setEntity(yourEntity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();}
Log.i(TAG, "File Sent to Server");
Toast.makeText(MainActivity.this, "File Sent to Server", Toast.LENGTH_LONG).show();
}
});
};
When I run the code the application everything appears fine, but when I press the button nothing happens and I get an error on the trace.
The error is as follows:
04-14 17:20:39.504: W/IInputConnectionWrapper(1693): showStatusIcon on inactive InputConnection
04-14 17:20:46.121: W/System.err(1693): java.net.SocketException: Permission denied
04-14 17:20:46.121: W/System.err(1693): at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
04-14 17:20:46.121: W/System.err(1693): at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
04-14 17:20:46.121: W/System.err(1693): at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
04-14 17:20:46.121: W/System.err(1693): at java.net.Socket.checkOpenAndCreate(Socket.java:802)
04-14 17:20:46.121: W/System.err(1693): at java.net.Socket.connect(Socket.java:948)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-14 17:20:46.121: W/System.err(1693): at school.project.application.MainActivity$1.onClick(MainActivity.java:117)
04-14 17:20:46.121: W/System.err(1693): at android.view.View.performClick(View.java:2485)
04-14 17:20:46.131: W/System.err(1693): at android.view.View$PerformClick.run(View.java:9081)
04-14 17:20:46.131: W/System.err(1693): at android.os.Handler.handleCallback(Handler.java:587)
04-14 17:20:46.131: W/System.err(1693): at android.os.Handler.dispatchMessage(Handler.java:92)
04-14 17:20:46.131: W/System.err(1693): at android.os.Looper.loop(Looper.java:130)
04-14 17:20:46.131: W/System.err(1693): at android.app.ActivityThread.main(ActivityThread.java:3696)
04-14 17:20:46.131: W/System.err(1693): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 17:20:46.131: W/System.err(1693): at java.lang.reflect.Method.invoke(Method.java:507)
04-14 17:20:46.131: W/System.err(1693): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
04-14 17:20:46.131: W/System.err(1693): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
04-14 17:20:46.131: W/System.err(1693): at dalvik.system.NativeStart.main(Native Method)
04-14 17:20:46.131: I/sendButton(1693): File Sent to Server

You may need to enable Internet access in the project's manifest file:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>

You need to have permission to send data via internet, Add the following line to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Related

android GCM Push notification crashing

I am working on android GCM to display some notification. It works fine. But when I add a code that could enable me to start the Home activity upon clicking the notification, it crashes. If I remove the PendingIntent It works fine but with no action.
Below is the code I am using
public class GcmMessageHandler extends GcmListenerService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
Intent intent = new Intent(GcmMessageHandler.this, HomeActivity.class);
int requestID = (int) System.currentTimeMillis(); //unique requestID to differentiate between various notification with same NotifId
int flags = PendingIntent.FLAG_CANCEL_CURRENT; // cancel old intent and create new one
PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, flags);
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
createNotification(from, message);
}
// Creates notification based on title and body received
private void createNotification(String title, String body) {
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pIntent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}
and below is the error log I am getting.
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: FATAL EXCEPTION: main
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: Process: abenakebe.yournet.com.abenakebe, PID: 14201
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: java.lang.RuntimeException: Unable to instantiate service abenakebe.yournet.com.abenakebe.utils.GcmMessageHandler: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.handleCreateService(ActivityThread.java:3623)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.access$2000(ActivityThread.java:198)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1759)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6837)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:101)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.PendingIntent.getActivity(PendingIntent.java:286)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.PendingIntent.getActivity(PendingIntent.java:252)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at abenakebe.yournet.com.abenakebe.utils.GcmMessageHandler.<init>(GcmMessageHandler.java:25)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Constructor.newInstance(Native Method)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.Class.newInstance(Class.java:1684)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.handleCreateService(ActivityThread.java:3620)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.access$2000(ActivityThread.java:198) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1759) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6837) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
You should move this two things at least to onCreate() or onMessageReceived()
Intent intent = new Intent(GcmMessageHandler.this, HomeActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, flags);
It crashes because this doesn't have Context before onCreate was called.
SHould be like this:
public class GcmMessageHandler extends GcmListenerService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
Intent intent;
int requestID = (int) System.currentTimeMillis(); //unique requestID to differentiate between various notification with same NotifId
int flags = PendingIntent.FLAG_CANCEL_CURRENT; // cancel old intent and create new one
PendingIntent pIntent;
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
intent = new Intent(GcmMessageHandler.this, HomeActivity.class);
pIntent = PendingIntent.getActivity(this, requestID, intent, flags);
createNotification(from, message);
}
// Creates notification based on title and body received
private void createNotification(String title, String body) {
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pIntent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}

Intent is not passing

I having a problem in passing the intent. The code is written in proper manner still it is showing errors in the logcat. Any help will be greatfull. Thank you
Have i placed the intent code in the write area???
Here is my main file.
MainActivity.java
public class MainActivity extends Activity {
ProgressBar progressBar;
int progressStatus = 0;
TextView textView1, textView2;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
textView2 = (TextView) findViewById(R.id.load_per);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView2.setText(progressStatus + "%");
if (progressStatus == 100) {
Intent i = new Intent(MainActivity.this,
EventActivity.class);
startActivity(i);
}
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
The logcat is showing errors like this
05-30 13:39:51.296: E/AndroidRuntime(1352): FATAL EXCEPTION: main
05-30 13:39:51.296: E/AndroidRuntime(1352): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.temp9/com.example.temp9.EventActivity}: java.lang.NullPointerException
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.ActivityThread.access$600(ActivityThread.java:122)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.os.Handler.dispatchMessage(Handler.java:99)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.os.Looper.loop(Looper.java:137)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.ActivityThread.main(ActivityThread.java:4340)
05-30 13:39:51.296: E/AndroidRuntime(1352): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 13:39:51.296: E/AndroidRuntime(1352): at java.lang.reflect.Method.invoke(Method.java:511)
05-30 13:39:51.296: E/AndroidRuntime(1352): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-30 13:39:51.296: E/AndroidRuntime(1352): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-30 13:39:51.296: E/AndroidRuntime(1352): at dalvik.system.NativeStart.main(Native Method)
05-30 13:39:51.296: E/AndroidRuntime(1352): Caused by: java.lang.NullPointerException
05-30 13:39:51.296: E/AndroidRuntime(1352): at com.example.temp9.EventActivity.onCreate(EventActivity.java:22)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.Activity.performCreate(Activity.java:4465)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-30 13:39:51.296: E/AndroidRuntime(1352): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
05-30 13:39:51.296: E/AndroidRuntime(1352): ... 11 more
Problem is Caused by: java.lang.NullPointerException
Here com.example.temp9.EventActivity.onCreate(EventActivity.java:22) in EventActivity class' onCreate function at line 22 location you are accessing some null pointer.
Seems like you haven't added EventActivity in AndroidManifest.xml(failed to start activity message in logcat). Make sure you have added the activity in Manifest file.

Create ListPreferences in Android

I'm trying to create a ListPreference in Android. But instead of creating all in XML i want to add the Entries and EntriesValues in JAVA. I have this XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<ListPreference android:key="delay"
android:title="#string/settings_push_delay"
android:defaultValue="Default">
</ListPreference>
</PreferenceScreen>
Then i have this class, extending PreferenceActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
final ListPreference listPreference = (ListPreference) findPreference("delay");
listPreference.setOnPreferenceClickListener(this);
}
public boolean onPreferenceClick(Preference preference) {
ListPreference lp = (ListPreference)preference;
String[] array={"1","2","3"};
CharSequence[] entries = array;
CharSequence[] entryValues = array;
lp.setEntries(entries);
lp.setDefaultValue("1");
lp.setEntryValues(entryValues);
return true;
}
This is just a test that i'm trying to do, so i can fully understand how to create Preferences dynamically.
Forgot to say that i've having exceptions while running this code:
04-14 00:47:10.432: E/AndroidRuntime(1330): FATAL EXCEPTION: main
04-14 00:47:10.432: E/AndroidRuntime(1330): java.lang.IllegalStateException: ListPreference requires an entries array and an entryValues array.
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.preference.ListPreference.onPrepareDialogBuilder(ListPreference.java:232)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.preference.DialogPreference.showDialog(DialogPreference.java:293)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.preference.DialogPreference.onClick(DialogPreference.java:264)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.preference.Preference.performClick(Preference.java:939)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:202)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.widget.AdapterView.performItemClick(AdapterView.java:292)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.widget.AbsListView$1.run(AbsListView.java:3168)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.os.Handler.handleCallback(Handler.java:605)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.os.Handler.dispatchMessage(Handler.java:92)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.os.Looper.loop(Looper.java:137)
04-14 00:47:10.432: E/AndroidRuntime(1330): at android.app.ActivityThread.main(ActivityThread.java:4424)
04-14 00:47:10.432: E/AndroidRuntime(1330): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 00:47:10.432: E/AndroidRuntime(1330): at java.lang.reflect.Method.invoke(Method.java:511)
04-14 00:47:10.432: E/AndroidRuntime(1330): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-14 00:47:10.432: E/AndroidRuntime(1330): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-14 00:47:10.432: E/AndroidRuntime(1330): at dalvik.system.NativeStart.main(Native Method)
My question is, how i create a ListPreference without defining the Entries and EntryValues on the XML. How can do that in JAVA file. So, how i solve this exceptions?
Thanks,
You cannot be setting the entries and entryValues of the ListPreference in an onClick event when there are no entries and entryValues to begin with.
Instead do it in the onCreate.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
final ListPreference listPreference = (ListPreference) findPreference("delay");
String[] array={"1","2","3"};
CharSequence[] entries = array;
CharSequence[] entryValues = array;
listPreference.setEntries(entries);
listPreference.setDefaultValue("1");
listPreference.setEntryValues(entryValues);
}
Then if you need set values dynamically in onClick listener, it should work okay.

Button click causing null pointer

Every time I click on the button, the app crashes. I have trouble finding the bug, but I'm sure it has to do something with either the onClickListener, or the onClick function.
Note: I'm using Parse API for some back end stuff. But I highly doubt it has anything to do with any of the Parse stuff.
Here's what my code looks like:
public class SignUpActivity extends Activity {
protected EditText mUserName;
protected EditText mPassword;
protected EditText mEmail;
protected Button mSignUpButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_sign_up);
mUserName = (EditText) findViewById(R.id.usernameField);
mPassword = (EditText) findViewById(R.id.passwordField);
mEmail = (EditText) findViewById(R.id.emailField);
mSignUpButton = (Button) findViewById(R.id.signupButton);
mSignUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUserName.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();
if(username.isEmpty() || password.isEmpty() || email.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else{
setProgressBarIndeterminateVisibility(true);
ParseUser newUser = new ParseUser();
newUser.setUsername(username);
newUser.setPassword(password);
newUser.setEmail(email);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if(e == null){
// success
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sign_up, menu);
return true;
}
}
Here's my Log Cat:
04-14 14:19:05.881: E/AndroidRuntime(1156): FATAL EXCEPTION: main 04-14 14:19:05.881:
E/AndroidRuntime(1156): Process: com.ebad.ribbit, PID: 1156 04-14 14:19:05.881:
E/AndroidRuntime(1156): java.lang.NullPointerException 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:40) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.view.View.performClick(View.java:4438) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.view.View$PerformClick.run(View.java:18422) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.handleCallback(Handler.java:733) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.dispatchMessage(Handler.java:95) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Looper.loop(Looper.java:136) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invokeNative(Native Method) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invoke(Method.java:515) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at dalvik.system.NativeStart.main(Native Method)
EDIT:
As requested, here is line 40:
String username = mUserName.getText().toString();
EDIT 2:
Here is the log cat after adding Log.i(TAG, mUserName == null ? "mUserName is null" : mUserName.getText() == null ? "mUserName.getText() is null" : "nothing is null"); :
04-14 15:21:47.955: E/AndroidRuntime(1318): FATAL EXCEPTION: main
04-14 15:21:47.955: E/AndroidRuntime(1318): Process: com.ebad.ribbit, PID: 1318
04-14 15:21:47.955: E/AndroidRuntime(1318): java.lang.NullPointerException
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:43)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.view.View.performClick(View.java:4438)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.view.View$PerformClick.run(View.java:18422)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Handler.handleCallback(Handler.java:733)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Handler.dispatchMessage(Handler.java:95)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Looper.loop(Looper.java:136)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-14 15:21:47.955: E/AndroidRuntime(1318): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 15:21:47.955: E/AndroidRuntime(1318): at java.lang.reflect.Method.invoke(Method.java:515)
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-14 15:21:47.955: E/AndroidRuntime(1318): at dalvik.system.NativeStart.main(Native Method)
EDIT 3:
Upon Request, here is my activity_sign_up.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SignUpActivity" >
<EditText
android:id="#+id/userNameField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="#string/username_hint"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/passwordField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/userNameField"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<EditText
android:id="#+id/emailField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/passwordField"
android:ems="10"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/signupButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/emailField"
android:layout_below="#+id/emailField"
android:layout_marginTop="50dp"
android:text="#string/sign_up_button_label" />
</RelativeLayout>
Do this please:
#Override
public void onClick(View v) {
if(mUserName != null && mPassword != null && mEmail != null && mUserName.getText() != null && mPassword.getText() != null && mEmail.getText() != null)
{
Your original code here.
}
}
Update:
Typo
mUserName = (EditText) findViewById(R.id.usernameField); should be userNameField?
<EditText android:id="#+id/userNameField" ...
If mUsername is null, calling getText() on it will cause a NullPointerException. You should check that it's not null before doing this. Try changing to the following:
if(mUserName == null || mPassword == null || mEmail == null){
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
String username = mUserName.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();
Try
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
https://developer.android.com/guide/topics/ui/dialogs.html
Also make sure that SignUpActivity is declared in the app manifest. I guess make sure that all activities are set up in the manifest.
EDIT 1
If line 40 is the issue, then
mUserName is null
or
mUserName.getText() is null. So create a couple checks before hand and also add some debug logs to just verify that they are not null.
Make sure that R.layout.activity_sign_up has usernameField as an id. Also make sure in any other app/res/layout folders (ie layout-v14), that all R.layout.activity_sign_up has the edittext as well.
If this errors occurred in your line 40, that means your are getting null from your EditText.
Try it in every place you are getting a string. At least it will save you from getting null pointer exception from EditText.
String username = String.valueOf(mUserName.getText());
String password = String.valueOf(mPassword.getText());
String email = String.valueOf(mEmail.getText());

App force closing on ViewPager?

So far this app's sole task is to slide as i swipe the screen horizontally. But when i run it on my Android Virtual machine logcat pops up with these errors.:
04-14 16:14:17.822: D/ddm-heap(196): Got feature list request
04-14 16:14:18.193: D/AndroidRuntime(196): Shutting down VM
04-14 16:14:18.193: W/dalvikvm(196): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-14 16:14:18.193: E/AndroidRuntime(196): Uncaught handler: thread main exiting due to uncaught exception
04-14 16:14:18.313: E/AndroidRuntime(196): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{stc1.hello.here/stc1.hello.here.Stc1Activity}: java.lang.ClassNotFoundException: stc1.hello.here.Stc1Activity in loader dalvik.system.PathClassLoader#44c067e8
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.os.Handler.dispatchMessage(Handler.java:99)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.os.Looper.loop(Looper.java:123)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-14 16:14:18.313: E/AndroidRuntime(196): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 16:14:18.313: E/AndroidRuntime(196): at java.lang.reflect.Method.invoke(Method.java:521)
04-14 16:14:18.313: E/AndroidRuntime(196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-14 16:14:18.313: E/AndroidRuntime(196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-14 16:14:18.313: E/AndroidRuntime(196): at dalvik.system.NativeStart.main(Native Method)
04-14 16:14:18.313: E/AndroidRuntime(196): Caused by: java.lang.ClassNotFoundException: stc1.hello.here.Stc1Activity in loader dalvik.system.PathClassLoader#44c067e8
04-14 16:14:18.313: E/AndroidRuntime(196): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
04-14 16:14:18.313: E/AndroidRuntime(196): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
04-14 16:14:18.313: E/AndroidRuntime(196): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
04-14 16:14:18.313: E/AndroidRuntime(196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
04-14 16:14:18.313: E/AndroidRuntime(196): ... 11 more
04-14 16:14:18.403: I/dalvikvm(196): threadid=7: reacting to signal 3
04-14 16:14:18.413: E/dalvikvm(196): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
04-14 16:14:35.972: D/AndroidRuntime(228): Shutting down VM
04-14 16:14:36.052: W/dalvikvm(228): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-14 16:14:36.052: E/AndroidRuntime(228): Uncaught handler: thread main exiting due to uncaught exception
04-14 16:14:36.112: E/AndroidRuntime(228): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{stc1.hello.here/stc1.hello.here.Stc1Activity}: java.lang.ClassNotFoundException: stc1.hello.here.Stc1Activity in loader dalvik.system.PathClassLoader#44e8c7e8
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.os.Handler.dispatchMessage(Handler.java:99)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.os.Looper.loop(Looper.java:123)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-14 16:14:36.112: E/AndroidRuntime(228): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 16:14:36.112: E/AndroidRuntime(228): at java.lang.reflect.Method.invoke(Method.java:521)
04-14 16:14:36.112: E/AndroidRuntime(228): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-14 16:14:36.112: E/AndroidRuntime(228): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-14 16:14:36.112: E/AndroidRuntime(228): at dalvik.system.NativeStart.main(Native Method)
04-14 16:14:36.112: E/AndroidRuntime(228): Caused by: java.lang.ClassNotFoundException: stc1.hello.here.Stc1Activity in loader dalvik.system.PathClassLoader#44e8c7e8
04-14 16:14:36.112: E/AndroidRuntime(228): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
04-14 16:14:36.112: E/AndroidRuntime(228): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
04-14 16:14:36.112: E/AndroidRuntime(228): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
04-14 16:14:36.112: E/AndroidRuntime(228): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
04-14 16:14:36.112: E/AndroidRuntime(228): ... 11 more
04-14 16:14:36.174: I/dalvikvm(228): threadid=7: reacting to signal 3
04-14 16:14:36.174: E/dalvikvm(228): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
Here is FragmentActivity.java:
package stc1.hello.here;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;
public class FragmentActivity extends Activity {
//We declare how many pages we want here.
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS = 20;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.layout.main1);
awesomePager.setAdapter(awesomeAdapter);
}
private class AwesomePagerAdapter extends PagerAdapter{
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {#link #finishUpdate()}.
*
* #param container The containing View in which the page will be shown.
* #param position The page position to be instantiated.
* #return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
#Override
public Object instantiateItem(View collection, int position) {
TextView tv = new TextView(cxt);
tv.setText("Bonjour PAUG " + position);
tv.setTextColor(Color.WHITE);
tv.setTextSize(30);
((ViewPager) collection).addView(tv,0);
return tv;
}
/**
* Remove a page for the given position. The adapter is responsible
* for removing the view from its container, although it only must ensure
* this is done by the time it returns from {#link #finishUpdate()}.
*
* #param container The containing View from which the page will be removed.
* #param position The page position to be removed.
* #param object The same object that was returned by
* {#link #instantiateItem(View, int)}.
*/
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((TextView) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==((TextView)object);
}
/**
* Called when the a change in the shown pages has been completed. At this
* point you must ensure that all of the pages have actually been added or
* removed from the container as appropriate.
* #param container The containing View which is displaying this adapter's
* page views.
*/
#Override
public void finishUpdate(View arg0) {}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {}
}
}
Here is main1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+android:id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
Your activity name doesn't match the activity name given in the error:
Caused by: java.lang.ClassNotFoundException: stc1.hello.here.Stc1Activity
You probably need to update the manifest with the correct name.

Categories