onlcick drawer navigation start new activity - Java for Android App Development

hello friends i'm new here and sorry for my question i'm big beginner and an autolearner.
i'm doing an app for android basicaly mock up. and i created a projectwith drawer menu and menu item are stocked in string not in array.
when i run it if i click on an item the number of row of the item appear in the mainactivity.xml what i realy want is to start a new activity here is my code i hope i can get help here,
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;

canempire said:
hello friends i'm new here and sorry for my question i'm big beginner and an autolearner.
i'm doing an app for android basicaly mock up. and i created a projectwith drawer menu and menu item are stocked in string not in array.
when i run it if i click on an item the number of row of the item appear in the mainactivity.xml what i realy want is to start a new activity here is my code i hope i can get help here,
Click to expand...
Click to collapse
Modify your onNavigationDrawerItemSelected method as follows
PHP:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
Fragment yourfragment = new Yourfragment();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
,beginTransaction();
fragmentTransaction.replace(R.id.container, yourfragment );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,destination.class);
startActivity(intent);
break;
case 2:
//To do something else like a dialog or a toast
Toast.maketext(context,"Sample Toast",Tosat.LENGTH_LONG).show();
break;
}
}

hello friend thank you very much for your response i edited my code like this
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
FragmentVue1 FragmentVue1 = new FragmentVue1();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fragmentTransaction = fragmentManager;
beginTransaction();
fragmentTransaction.replace(R.id.container, FragmentVue1 );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity.intent();
break;
FragmentVue1 is the name of my activity 1 and the activity load the layout, the code i posted up is little edited than than that you gave me on up reply, because eclipse stress it that suggested me some code to change for exemple
HTML:
Fragment Frgment1 = new FragmentVue1();
raplace in this code is still empty and eclipse ask me to Add cast method receiver
HTML:
fragmentTransaction.replace(R.id.container, FragmentVue1 );
and in this code too fro commit
HTML:
fragmentTransaction.commit();
for this code
HTML:
startActivity.intent();
eclipse is asking me to crete local variable startActivity, create field starActivity,create parameter startActivity create class, and constant .
i'm sorry if i bring to difficult place i really need it to change layout(fragment) to start it just for show a mock up

canempire said:
hello friend thank you very much for your response i edited my code like this
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
FragmentVue1 FragmentVue1 = new FragmentVue1();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fragmentTransaction = fragmentManager;
beginTransaction();
fragmentTransaction.replace(R.id.container, FragmentVue1 );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity.intent();
break;
FragmentVue1 is the name of my activity 1 and the activity load the layout, the code i posted up is little edited than than that you gave me on up reply, because eclipse stress it that suggested me some code to change for exemple
HTML:
Fragment Frgment1 = new FragmentVue1();
raplace in this code is still empty and eclipse ask me to Add cast method receiver
HTML:
fragmentTransaction.replace(R.id.container, FragmentVue1 );
and in this code too fro commit
HTML:
fragmentTransaction.commit();
for this code
HTML:
startActivity.intent();
eclipse is asking me to crete local variable startActivity, create field starActivity,create parameter startActivity create class, and constant .
i'm sorry if i bring to difficult place i really need it to change layout(fragment) to start it just for show a mock up
Click to expand...
Click to collapse
I guess using
"startActivity(intent);"
instead of
"startActivity.intent();" will please eclipse
and not to mention will solve the issue
I bet u didn google that
Sent from my GT-S5302 using Tapatalk 2

canempire said:
hello friend thank you very much for your response i edited my code like this
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
FragmentVue1 FragmentVue1 = new FragmentVue1();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fragmentTransaction = fragmentManager;
beginTransaction();
fragmentTransaction.replace(R.id.container, FragmentVue1 );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity.intent();
break;
FragmentVue1 is the name of my activity 1 and the activity load the layout, the code i posted up is little edited than than that you gave me on up reply, because eclipse stress it that suggested me some code to change for exemple
HTML:
Fragment Frgment1 = new FragmentVue1();
raplace in this code is still empty and eclipse ask me to Add cast method receiver
HTML:
fragmentTransaction.replace(R.id.container, FragmentVue1 );
and in this code too fro commit
HTML:
fragmentTransaction.commit();
for this code
HTML:
startActivity.intent();
eclipse is asking me to crete local variable startActivity, create field starActivity,create parameter startActivity create class, and constant .
i'm sorry if i bring to difficult place i really need it to change layout(fragment) to start it just for show a mock up
Click to expand...
Click to collapse
you don't need to use any code present in case 0 if you are not loading a fragment. I just wrote that to make sure you know the difference between starting an activity and a fragment.
If you just want too start an activity just use what is inside case 1.
and as @sak-venom1997 said it should be startActivity(intent) instead of startActivity.intent(). My bad (i am a confused person )
so suppose FragmentVue1 is your activity's name and you want to open it on clicking nth item of navigation drawer use
PHP:
case n:
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;

gh0stslayer said:
you don't need to use any code present in case 0 if you are not loading a fragment. I just wrote that to make sure you know the difference between starting an activity and a fragment.
If you just want too start an activity just use what is inside case 1.
and as @sak-venom1997 said it should be startActivity(intent) instead of startActivity.intent(). My bad (i am a confused person )
so suppose FragmentVue1 is your activity's name and you want to open it on clicking nth item of navigation drawer use
PHP:
case n:
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
Click to expand...
Click to collapse
thank you very much for yours reply both are usefully @sak-venom1997
yes FragmentVue1 is my activity it load a layout the reality is i know difference between Activity and Layout but no the both with Fragment.
now it working but the MainActivity is empty when i start the app and i find a warning in code below case 1 break i copied the warning in message in the below code in the line of warning
PHP:
private void onSectionAttached(int i) {
// TODO Auto-generated method stub
}
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}

canempire said:
thank you very much for yours reply both are usefully @sak-venom1997
yes FragmentVue1 is my activity it load a layout the reality is i know difference between Activity and Layout but no the both with Fragment.
now it working but the MainActivity is empty when i start the app and i find a warning in code below case 1 break i copied the warning in message in the below code in the line of warning
PHP:
private void onSectionAttached(int i) {
// TODO Auto-generated method stub
}
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}
Click to expand...
Click to collapse
If i understand you the right way, you are extending Fragment. In this case you are overriding some methods, but dont modify them. How did you get the code? Via the eclipse menu saying "override/implement methods"? Or did you copy the code from somewhere? If you really need to keep the code, i think you have to call super in the method.
Gesendet von meinem SM-N9005 mit Tapatalk

GalaxyInABox said:
If i understand you the right way, you are extending Fragment. In this case you are overriding some methods, but dont modify them. How did you get the code? Via the eclipse menu saying "override/implement methods"? Or did you copy the code from somewhere? If you really need to keep the code, i think you have to call super in the method.
Gesendet von meinem SM-N9005 mit Tapatalk
Click to expand...
Click to collapse
the code is generated when i created the project it is a part of MainActivity.java code it didn't have warning message before i add
PHP:
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
but why the main activity (fragment) is empty?? now :crying:

can someone help me please???

FragmentVue1 isi an Activity it is FragmentVue1.java and the code is
PHP:
package com.projectmockup.cypruscityguide;
import com.projectmockup.cypruscityguide.R;
import android.app.Activity;
import android.os.Bundle;
public class FragmentVue1 extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel);
}
}
please help when i start the application the Fragment_main.xml is empty but before i use this code in MainActivity
PHP:
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
the content of Fragment_main.xml was visible
i check below in the MainActivity and i found this code with alert
PHP:
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}

canempire said:
FragmentVue1 isi an Activity it is FragmentVue1.java and the code is
PHP:
package com.projectmockup.cypruscityguide;
import com.projectmockup.cypruscityguide.R;
import android.app.Activity;
import android.os.Bundle;
public class FragmentVue1 extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel);
}
}
please help when i start the application the Fragment_main.xml is empty but before i use this code in MainActivity
PHP:
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
the content of Fragment_main.xml was visible
i check below in the MainActivity and i found this code with alert
PHP:
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}
Click to expand...
Click to collapse
You don't need to add these lines, they are for opening a fragment. I just provided them to help you know how to open a fragment from navigation drawer.

Related

[Q] Copy Image from Gallery Share (Send To) menu

Moderators... It says I am breaking the rules by asking a question and to ask in the Q&A... But the title of this is "Coding Discussion, Q&A, and Educational Resources" I am not breaking the rules intentionally, I just don't know where else to put this. This is a Coding Question, not a General Question that I would think would get buried and or lost in the General Q&A forum. Please move if you feel I am incorrect.
Hello All, I was hoping someone could help me.
I am trying to create an app that will hide pictures. I want to be able to Pick my App from the Share (Send To) menu from the Users Gallery and have it copy the file to a Directory I have created on my SDCard and then ultimately delete the file from the current location.
Here is what I have so far, but when I pick my app from the Share menu, it crashes the Gallery app. So... I can't even see any errors in my LogCat to even try and troubleshoot my issue.
Can someone point me to a working example of how to do this (I have searched the internet until I am blue in the face) or... I hate to say it... Fix my Code?
Any Help would be appreciated... Thanks!!
Code:
package com.company.privitegallery;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class SendToDo extends Activity {
File sdCardLoc = Environment.getExternalStorageDirectory();
File intImagesDir = new File(sdCardLoc,"/DCIM/privgal/.nomedia");
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
try {
GetPhotoPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
//...
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
public void GetPhotoPath() throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
copy(fileName, intImagesDir);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
try {
copy(selectedImagePath, intImagesDir);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(String scr, File dst) throws IOException {
InputStream in = new FileInputStream(scr);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void deleteLatest() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
//Log.i("Log", "file name in delete folder : "+f.toString());
File [] files = f.listFiles();
//Log.i("Log", "List of files is: " +files.toString());
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
// Log.i("Log", "Going -1");
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
// Log.i("Log", "Going +1");
return 1;
} else {
// Log.i("Log", "Going 0");
return 0;
}
}
});
//Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
files[0].delete();
}
}
What's the gallery log output?
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
nikwen said:
What's the gallery log output?
Click to expand...
Click to collapse
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
nikwen said:
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
Click to expand...
Click to collapse
Great, Thanks!!
StEVO_M said:
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
Great, Thanks!!
Click to expand...
Click to collapse
Do you view the logs on your computer?
There should be an error message in the logs.
nikwen said:
Do you view the logs on your computer?
There should be an error message in the logs.
Click to expand...
Click to collapse
Which Logs?? As I said before. LogCat does not give any errors.

How to record the Android Touch event?

I have to record the touch event of any android (.apk) application. For that I have created the .jar(Library) file which is responsible to record touch event when user press any control. This .jar will be injected with any .apk file.
For achieve the above things I have follow the below step.
1)I have created application with only one button name App.apk.
2)Also Create the another library project called Test.jar
3)Give the dependency of Test.jar to App.apk.
Now I want send same event to test.jar. I have write below code in App.apk activity
@override
public void onResume()
{
super.onResume();
Test.Event.MyHook(this);
}
@override
public void onPause()
{
super.onPause();
Test.Event.MyUnHook(this);
}
@override
public boolean dispatchKeyEvent(android.view.KeyEvent event)
{
Test.Event.MyEvent(event);
return super.dispatchKeyEvent(event);
}
Can u suggest the way to get button click event from App.apk to Test.jar ?
Thanks
maheng said:
I have to record the touch event of any android (.apk) application. For that I have created the .jar(Library) file which is responsible to record touch event when user press any control. This .jar will be injected with any .apk file.
For achieve the above things I have follow the below step.
1)I have created application with only one button name App.apk.
2)Also Create the another library project called Test.jar
3)Give the dependency of Test.jar to App.apk.
Now I want send same event to test.jar. I have write below code in App.apk activity
@override
public void onResume()
{
super.onResume();
Test.Event.MyHook(this);
}
@override
public void onPause()
{
super.onPause();
Test.Event.MyUnHook(this);
}
@override
public boolean dispatchKeyEvent(android.view.KeyEvent event)
{
Test.Event.MyEvent(event);
return super.dispatchKeyEvent(event);
}
Can u suggest the way to get button click event from App.apk to Test.jar ?
Thanks
Click to expand...
Click to collapse
Seems rather fishy why you'd have to do that, but let's roll with it...^^
TLDR: in pure java, using standard APIs or even reflection or root, you can't.
You could use the android-event-injector project (which is a C++/JNI library) : https://code.google.com/p/android-event-injector/
It provides methods to listen to all input events, something like that (this will send all the results to logcat):
PHP:
public void StartEventMonitor() {
m_bMonitorOn = true;
Thread b = new Thread(new Runnable() {
public void run() {
while (m_bMonitorOn) {
for (InputDevice idev:events.m_Devs) {
// Open more devices to see their messages
if (idev.getOpen() && (0 == idev.getPollingEvent())) {
final String line = idev.getName()+
":" + idev.getSuccessfulPollingType()+
" " + idev.getSuccessfulPollingCode() +
" " + idev.getSuccessfulPollingValue();
Log.d(LT, "Event:"+line);
}
}
}
}
});
b.start();
}
You can read more here: http://www.pocketmagic.net/2013/01/programmatically-injecting-events-on-android-part-2/
However, you might also be able to do that using the Xposed framework and finding a hook into the actual framework class for dispatchKeyEvent if it's the event you want to intercept.
I've never with Xposed so I can't really help you with the implementation, though, but it might be something to look into.

File Save code is not saving file in internal storage

i want to save a layout (relative layout), when i run the app everything is working fine, but i am unable to find saved file/s in the internal storage of the phone. Any help would be appreciated as i am new and unable to sort out what is going wrong . here is my code
Code:
public void saveMe(View v) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.prompt, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompt.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialog);
// set dialog message
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final String fileName = userInput.getText().toString();
final View view1=findViewById(R.id.relativeLayout); // The view that you want to save as an image
Bitmap bitmap = Bitmap.createBitmap(view1.getWidth(), view1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
view1.draw(c);
if(fileName.length() == 0)
Toast.makeText(EidCardFinal.this,"Please Enter File Name",Toast.LENGTH_SHORT).show();
else{
File file = new File(context.getFilesDir(), fileName);
if (file.exists())
Toast.makeText(EidCardFinal.this,"File Already Exists",Toast.LENGTH_SHORT).show();
else{
try{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, out);
Toast.makeText(EidCardFinal.this,"File Saved",Toast.LENGTH_SHORT).show();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
Try adding a line:
out.flush();
just before calling close() on the FileOutputStream. I think this will get the save code to work, and it's worth trying.
ExoComet said:
Try adding a line:
out.flush();
just before calling close() on the FileOutputStream. I think this will get the save code to work, and it's worth trying.
Click to expand...
Click to collapse
thanks for the suggestion, but i have opted for the external storage and its working fine

[Q] need help im new to the app dev world

im having issues with my coding for an app im trying to develop and since im a noob i cant just identify errors i would like to post my logcat but cause of the errors it wont run .... my code is for a login and registration please just point out my errors im down to learn and understand whats going on ....
my login activity
public class LoginScreen extends Activity {
Button btnSignIn ;
TextView registerScreen;
LoginDataBaseAdapter loginDataBaseAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), SignUp.class);
startActivity(i);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn = (Button) findViewById(R.id.btnLogin);
}
// Methods to handleClick Event of Sign In Button
public void signIn(View V) {
try{
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
Button btnSignIn = (Button) dialog.findViewById(R.id.btnLogin);
}catch(Exception e){
Log.e("tag", e.getMessage());
}
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
dialog.show();
}
}
@override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("tag", e.getMessage());
}
}
@override
protected void onDestroy() {
try{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
} }
my registration activity
public class SignUp extends Activity {
EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
Button btnRegister;
LoginDataBaseAdapter loginDataBaseAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
// get Instance of Database Adapter
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get References of Views
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
// check if any of the fields are vacant
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}
}
@override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}}
Could you please be more specific about your errors? Error output from eclipse in case of compile error or if it did compile but has runtime errors then post the logcat output for example. This would help
Edit::
Well for the first i wouldnt distribute the onclick listeners so much, instead let your activity implement OnClickListener so you have one onClick method for all, that is far more ordered. Then put a switch inside it: switch (v.getId()) { //v is the clicked button
case R.id.btnLogin:
//login button code here
case R.id. .... :
......
}
Then it is more structured
---------------------------------
Phone : Nexus 4
OS :
- KitKat 4.4.4 stock
- Xposed: 58(app_process); 54(bridge)
- SU: SuperSU
- no custom recovery
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Wich IDE are you using ?
If you can't run it it means that it's a compilation failure, probably a syntax error. Most of Java IDE tells you where is the error even before you run it.
updated
WaitTobi said:
*Updated*here's where im at now in regard to my register/loginscreen right at this moment i still cannot run the app and test it out at the moment my login screen seems clean no errors in and but still my register class still has a couple errors one is underlined class name saying to "add implemented methods" and the other one is at my "TextView loginScreen;" right under the ";" and it says "syntax error, insert "}" to complete
ClassBody"
and also i would like to now how to make the classes actually connect to eachother... also Im using eclipse to run my project.. and if theres anything else that just looks wrong please point it out so i the future ill notice them
my login activity
public class LoginScreen extends Activity implements OnClickListener{
Button btnLogin ;
TextView registerScreen;
LoginDataBaseAdapter LoginDataBaseAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) this.findViewById(R.id.link_to_register);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
registerScreen.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
// create a instance of SQLite Database
LoginDataBaseAdapter = new LoginDataBaseAdapter(this);
LoginDataBaseAdapter = LoginDataBaseAdapter.open();
}
// Methods to handleClick Event of Sign In Button
public void Login(View V) {
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = LoginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
dialog.show();
}
@override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("StartActivity-Mainpage-error", e.getMessage());
}}
@override
protected void onDestroy() {
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
@override
public void onClick(View v) {
// TODO Auto-generated method stub
}}
my registration activity
public class SignUp extends Activity implements OnClickListener{
EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
Button btnRegister;
LoginDataBaseAdapter LoginDataBaseAdapter;
TextView loginScreen;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
TextView loginScreen = (TextView) this.findViewById(R.id.link_to_login);
// Listening to Login Screen link
btnRegister = (Button) findViewById(R.id.btnRegister);
// Get References of Views
loginScreen.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(SignUp.this, LoginScreen.class));
finish();
}
});
// get Instance of Database Adapter
LoginDataBaseAdapter = new LoginDataBaseAdapter(this);
LoginDataBaseAdapter = LoginDataBaseAdapter.open();
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// check if any of the fields are vacant
try{
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
LoginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}}
}catch(Exception e){
Log.e("onClickRegister-error", e.getMessage());
}
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{ // Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}catch(Exception e){
Log.e("onClickRegister button-error", e.getMessage());
}}
@override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy SignUp - Error", e.getMessage());
}
}
@override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Click to expand...
Click to collapse
Hvedrung said:
Wich IDE are you using ?
If you can't run it it means that it's a compilation failure, probably a syntax error. Most of Java IDE tells you where is the error even before you run it.
Click to expand...
Click to collapse
IM using eclipse for development
I did a couple of corrections from what I see, in red.
WaitTobi said:
*Updated*here's where im at now in regard to my register/loginscreen right at this moment i still cannot run the app and test it out at the moment my login screen seems clean no errors in and but still my register class still has a couple errors one is underlined class name saying to "add implemented methods" and the other one is at my "TextView loginScreen;" right under the ";" and it says "syntax error, insert "}" to complete
ClassBody"
and also i would like to now how to make the classes actually connect to eachother... also Im using eclipse to run my project.. and if theres anything else that just looks wrong please point it out so i the future ill notice them
Code:
my login activity
public class LoginScreen extends Activity [COLOR="red"][STRIKE]implements OnClickListener[/STRIKE][/COLOR]{
[COLOR="red"]private[/COLOR] Button btnLogin ;
[COLOR="red"]private [/COLOR]TextView registerScreen;
[COLOR="red"]private [/COLOR]LoginDataBaseAdapter LoginDataBaseAdapter;
[COLOR="red"]private LoginDataBaseAdapter dataBaseAdapter; // you need it here instead of in your method so you can access it everywhere[/COLOR]
[COLOR="red"]// you don't have to make them private but it is nicer and common practice ;)[/COLOR]
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
[COLOR="red"][STRIKE]TextView[/STRIKE][/COLOR] registerScreen = (TextView) this.findViewById(R.id.link_to_register);
[COLOR="red"]// you initialize a new variable in the scope of the method instead of using the instance vars you created above![/COLOR]
[COLOR="red"][STRIKE]Button[/STRIKE][/COLOR] btnLogin = (Button) findViewById(R.id.btnLogin);
[COLOR="red"]// what you were doing here is not right, set the OnClickListener only for the button: (I prefer having it locally and not the whole class)[/COLOR]
[COLOR="red"][STRIKE]btnLogin.setOnClickListener(this);[/STRIKE][/COLOR]
[COLOR="red"][STRIKE]registerScreen[/STRIKE]btnLogin[/COLOR].setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// This is called whenever btnLogin is clicked:
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
[COLOR="red"]// did you perhaps follow [URL="http://stackoverflow.com/questions/19152998/android-limiting-signup-for-one-user"]this question?[/URL] you should copy the LoginDataBaseAdapter class from it into your project if you don't have it already...[/COLOR]
// create a instance of SQLite Database
[COLOR="red"][STRIKE]LoginDataBaseAdapter [/STRIKE][/COLOR][COLOR="red"]dataBaseAdapter[/COLOR] = new LoginDataBaseAdapter(this);
[COLOR="red"][STRIKE]LoginDataBaseAdapter = [/STRIKE][/COLOR][COLOR="red"]dataBaseAdapter[/COLOR].open();
}
// Methods to handleClick Event of Sign In Button
public void [COLOR="red"][STRIKE]L[/STRIKE]l[/COLOR]ogin(View V) {[COLOR="red"]// method names start with lowercase![/COLOR]
[COLOR="red"]// you should use a builder for an alert dialog instead, read [URL="http://developer.android.com/guide/topics/ui/dialogs.html"]this doc about it![/URL][/COLOR]
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
[COLOR="red"]// again, read the doc, it [URL="http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents"]even tells you how to pass your login data back![/URL] You could also consider running this code in your dialog ;)[/COLOR]
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = LoginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
dialog.show();
}
[COLOR="red"][STRIKE] [user=439709]@override[/user]
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("StartActivity-Mainpage-error", e.getMessage());
}}[/STRIKE]// what the hell are you trying to do here? let android do its work alone![/COLOR]
[user=439709]@override[/user]
protected void onDestroy() {
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
[COLOR="red"][STRIKE]
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
}
[/STRIKE]// ne need for that since we have our OnClickListener locally in onCreate()[/COLOR]
}
my registration activity
public class SignUp extends Activity implements OnClickListener{
[COLOR="red"]private [/COLOR]EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
[COLOR="red"]private [/COLOR]Button btnRegister;
[COLOR="red"]private [/COLOR]LoginDataBaseAdapter [COLOR="red"][STRIKE]LoginD[/STRIKE]d[/COLOR]ataBaseAdapter; [COLOR="red"]// I prefer short names and variables are always lower case![/COLOR]
[COLOR="red"]private [/COLOR]TextView loginScreen;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
[COLOR="red"][STRIKE]TextView[/STRIKE][/COLOR] loginScreen = (TextView) this.findViewById(R.id.link_to_login); // s.a.
// Listening to Login Screen link
btnRegister = (Button) findViewById(R.id.btnRegister);
// Get References of Views
[COLOR="red"][STRIKE]loginScreen[/STRIKE]btnRegister[/COLOR].setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(SignUp.this, LoginScreen.class));
[COLOR="red"][STRIKE]finish();[/STRIKE]// no need for that[/COLOR]
}
});
// get Instance of Database Adapter
[COLOR="red"][STRIKE]LoginD[/STRIKE]d[/COLOR]ataBaseAdapter = new LoginDataBaseAdapter(this);
[COLOR="red"][STRIKE]LoginDataBaseAdapter = LoginD[/STRIKE]d[/COLOR]ataBaseAdapter.open();
[COLOR="red"]final [/COLOR]String fullname = reg_fullname.getText().toString();[COLOR="red"]// I think they have to be final to be used in th onClickListener[/COLOR]
[COLOR="red"]final [/COLOR]String username = reg_username.getText().toString();
[COLOR="red"]final [/COLOR]String password = reg_password.getText().toString();
[COLOR="red"]final [/COLOR]String email = reg_email.getText().toString();
[COLOR="red"]final [/COLOR]String confirmPassword = reg_confirmpassword.getText()
.toString();
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// check if any of the fields are vacant
try{
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
[COLOR="red"]} else// closing if(username...[/COLOR]
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
[COLOR="red"][STRIKE]LoginD[/STRIKE]d[/COLOR]ataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}[COLOR="red"][STRIKE]}[/STRIKE][/COLOR]
}catch(Exception e){
Log.e("onClickRegister-error", e.getMessage());
}
[COLOR="red"]// ??? that is a text view and should not get a clicklistener... not getting where this code should go lol[/COLOR]
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{ // Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}catch(Exception e){
Log.e("onClickRegister button-error", e.getMessage());
}}
[user=439709]@override[/user]
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy SignUp - Error", e.getMessage());
}
}
[COLOR="red"][STRIKE]
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
}[/STRIKE][/COLOR]
}
Click to expand...
Click to collapse
It seems like you need a bit more practice in Java , there you go...
SimplicityApks said:
I did a couple of corrections from what I see, in red.
It seems like you need a bit more practice in Java...
Click to expand...
Click to collapse
thanks means alot helped a lot im starting to notice the errors im actually laughin at myself with a couple of the errors.... im still getting a error in regard to the last couple curly brackets "Multiple markers at this line
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert "}" to complete
ClassBody
- Syntax error, insert ")" to complete
Expression"
i know it just a } somewhere or something but how can u just be able to tell where it need to be placed
WaitTobi said:
thanks means alot helped a lot im starting to notice the errors im actually laughin at myself with a couple of the errors.... im still getting a error in regard to the last couple curly brackets "Multiple markers at this line
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert "}" to complete
ClassBody
- Syntax error, insert ")" to complete
Expression"
i know it just a } somewhere or something but how can u just be able to tell where it need to be placed
Click to expand...
Click to collapse
Well it tells you which line it is, take a look at it (probably where you close your second on click listener in the second activity). Remember that each bracket, curly or round has to get closed before the statement can be finished with a ; . Another thing I just noticed, you now set the onClickListener for btnRegister twice in the second activity, you can't do that. Probably the code of the first one should be executed after the code in the other click listener.
SimplicityApks said:
Well it tells you which line it is, take a look at it (probably where you close your second on click listener in the second activity). Remember that each bracket, curly or round has to get closed before the statement can be finished with a ; . Another thing I just noticed, you now set the onClickListener for btnRegister twice in the second activity, you can't do that. Probably the code of the first one should be executed after the code in the other click listener.
Click to expand...
Click to collapse
okay got it i put the first one click into the second one and i got rid of the textview onclick your were curoius about now i can finally run the app but right on the start up i get the runtime error. my logcat said"
08-19 06:49:56.201: D/AndroidRuntime(12905): Shutting down VM
08-19 06:49:56.201: W/dalvikvm(12905): threadid=1: thread exiting with uncaught exception (group=0x41a24c08)
08-19 06:49:56.206: E/AndroidRuntime(12905): FATAL EXCEPTION: main
08-19 06:49:56.206: E/AndroidRuntime(12905): Process: com.Flawed.hearmeout, PID: 12905
08-19 06:49:56.206: E/AndroidRuntime(12905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Flawed.hearmeout/com.Flawed.hearmeout.LoginScreen}: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.access$900(ActivityThread.java:175)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Handler.dispatchMessage(Handler.java:102)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Looper.loop(Looper.java:146)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.main(ActivityThread.java:5602)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invoke(Method.java:515)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
08-19 06:49:56.206: E/AndroidRuntime(12905): at dalvik.system.NativeStart.main(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): Caused by: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.Flawed.hearmeout.LoginScreen.onCreate(LoginScreen.java:44)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Activity.performCreate(Activity.java:5451)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
08-19 06:49:56.206: E/AndroidRuntime(12905): ... 11 more
"
how do i realize the issue thru logcat and solution, i know im probably bothering you by now and getting on your nerve but i apologize im just tryna to understand this a bit more
WaitTobi said:
okay got it i put the first one click into the second one and i got rid of the textview onclick your were curoius about now i can finally run the app but right on the start up i get the runtime error. my logcat said"
08-19 06:49:56.201: D/AndroidRuntime(12905): Shutting down VM
08-19 06:49:56.201: W/dalvikvm(12905): threadid=1: thread exiting with uncaught exception (group=0x41a24c08)
08-19 06:49:56.206: E/AndroidRuntime(12905): FATAL EXCEPTION: main
08-19 06:49:56.206: E/AndroidRuntime(12905): Process: com.Flawed.hearmeout, PID: 12905
08-19 06:49:56.206: E/AndroidRuntime(12905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Flawed.hearmeout/com.Flawed.hearmeout.LoginScreen}: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.access$900(ActivityThread.java:175)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Handler.dispatchMessage(Handler.java:102)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Looper.loop(Looper.java:146)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.main(ActivityThread.java:5602)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invoke(Method.java:515)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
08-19 06:49:56.206: E/AndroidRuntime(12905): at dalvik.system.NativeStart.main(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): Caused by: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.Flawed.hearmeout.LoginScreen.onCreate(LoginScreen.java:44)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Activity.performCreate(Activity.java:5451)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
08-19 06:49:56.206: E/AndroidRuntime(12905): ... 11 more
"
how do i realize the issue thru logcat and solution, i know im probably bothering you by now and getting on your nerve but i apologize im just tryna to understand this a bit more
Click to expand...
Click to collapse
Well read the whole thing, at the line in bold it tells you that you have a NullPointerException at line 44 of the Login activity. You should read nikwen's guide on logcats and debugging .
SimplicityApks said:
Well read the whole thing, at the line in bold it tells you that you have a NullPointerException at line 44 of the Login activity. You should read nikwen's guide on logcats and debugging .
Click to expand...
Click to collapse
thanks those links are really helping
SimplicityApks said:
Well read the whole thing, at the line in bold it tells you that you have a NullPointerException at line 44 of the Login activity. You should read nikwen's guide on logcats and debugging .
Click to expand...
Click to collapse
okay im having an issue with llogin button and register do you have a link or any reading i can check out to make sure my signup and login button work and actually save info and go to my main activity after it either saves the registration or logins in successfully
WaitTobi said:
okay im having an issue with llogin button and register do you have a link or any reading i can check out to make sure my signup and login button work and actually save info and go to my main activity after it either saves the registration or logins in successfully
Click to expand...
Click to collapse
If you want to check that some data is actually present then just write it to the log. Eg.
Log.V("Testing", someString);
If it is working then someString will be printed after the "Testing" tag. If its not then you should check your logcat to find out why not.

[Q] How do I add an image picker to my app, show it in image view, then save it to pa

This is what I have:
Code:
package JEB.ssf;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.view.View.*;
import com.parse.*;
import android.content.*;
import android.support.v4.app.*;
import java.util.*;
import android.widget.AdapterView.*;
import android.util.*;
import com.google.android.gms.ads.*;
import com.google.ads.mediation.*;
import com.google.ads.*;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdListener;
import android.provider.*;
import android.database.*;
import android.graphics.*;
public class ProfilePage extends Activity
{
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2, adp3;
List<String> l1,l2, l3;
int pos;
EditText fname, lname, hf, hi, weight,
waist, wrist, hip, forearm, age, goal;
TextView userName, gender, category, unit;
String hftxt, hitxt, id, firstNameTxt, userNameTxt, posttxt, postnum;
Button share;
float obid;
int in;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
getActionBar().setDisplayHomeAsUpEnabled(true);
Parse.initialize(this, "abmPl8JnnhyaqjA0Pp8ZWmptKTCeV0p8eoMEHPaL", "icKQxW5AdPXHJtsGEqSX5LwJ2Dd8zt0USKd1PNeP");
fname = (EditText) findViewById(R.id.first_name);
lname = (EditText) findViewById(R.id.last_name);
hf = (EditText) findViewById(R.id.height_feet);
hi = (EditText) findViewById(R.id.height_inch);
weight = (EditText) findViewById(R.id.weight_lbs);
waist = (EditText) findViewById(R.id.waist);
wrist = (EditText) findViewById(R.id.wrist);
hip = (EditText) findViewById(R.id.hip);
forearm = (EditText) findViewById(R.id.forearm);
age = (EditText) findViewById(R.id.age);
userName = (TextView) findViewById(R.id.user_name);
gender = (TextView) findViewById(R.id.gender);
category = (TextView) findViewById(R.id.category);
unit =(TextView) findViewById(R.id.unit);
goal =(EditText) findViewById(R.id.goal);
share = (Button) findViewById(R.id.share);
Intent i = getIntent();
userNameTxt = i.getStringExtra("user_name");
userName.setText(userNameTxt);
button = (Button)findViewById(R.id.image_pick);
image = (ImageView)findViewById(R.id.image);
gender_button();
category_button();
unit_button();
image_button();
share_button();
small_banner_ad();
final ParseQuery<ParseObject> query = ParseQuery.getQuery("profile_info");
// Restrict to cases where the author is the current user.
// Note that you should pass in a ParseUser and not the
// String reperesentation of that user
query.whereEqualTo("user_data", ParseUser.getCurrentUser());
// Run the query
query.findInBackground(new FindCallback<ParseObject>() {
public String TAG;
[user=439709]@override[/user]
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
// If there are results, update the list of posts
// and notify the adapter
for (ParseObject profile_info : postList) {
userName.setText(profile_info.getString("user_name"));
fname.setText(profile_info.getString("first_name"));
lname.setText(profile_info.getString("last_name"));
hf.setText(profile_info.getString("height_in_feet"));
hi.setText(profile_info.getString("height_in_inches"));
weight.setText(profile_info.getString("weight"));
waist.setText(profile_info.getString("waist"));
wrist.setText(profile_info.getString("wrist"));
hip.setText(profile_info.getString("hip"));
forearm.setText(profile_info.getString("forearm"));
age.setText(profile_info.getString("age"));
gender.setText(profile_info.getString("gender"));
category.setText(profile_info.getString("category"));
unit.setText(profile_info.getString("unit"));
goal.setText(profile_info.getString("goal"));
}
} else {
Log.d("Post retrieval", "Error: " + e.getMessage());
}
}});
}
private void share_button()
{
share.setOnClickListener(new OnClickListener() {
public void onClick(View arg1) {
final ParseObject posts = new ParseObject("posts");
posts.put("user_name", userName.getText().toString());
posts.put("category", "My goal is to" + " "+category.getText()+" "+goal.getText()+" "+unit.getText().toString());
// Create an user data relationship with the current user
posts.put("user_posts", ParseUser.getCurrentUser());
// Save the post and return
posts.saveInBackground(new SaveCallback () {
[user=439709]@override[/user]
public void done(ParseException e) {
if (e == null) {
setResult(RESULT_OK);
Toast.makeText(getApplicationContext(),"post successfull",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error sharing: " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}});
}
});
}
private void unit_button()
{
unit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ProfilePage.this, unit);
//Inflating the Popup using xml file
if (category.getText().toString().equals("Loose Weight")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Target Weight")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Gain Weight")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Build Muscle")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Run")){
popup.getMenuInflater()
.inflate(R.menu.distance_menu, popup.getMenu());
}if(category.getText().toString().equals("Walk")){
popup.getMenuInflater()
.inflate(R.menu.distance_menu, popup.getMenu());
}
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbs:
//act for menu_item1
unit.setText("lbs");
return true;
case R.id.mile:
//act for sub_menu_item1
unit.setText("Mile");
return true;
case R.id.k:
//act for sub_menu_item1
unit.setText("K");
return true;
default:
//pass the event to parent, for options menu, use below
}
return false;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}
private void category_button()
{
category.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ProfilePage.this, category);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.category_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.target_weight:
category.setText("Target Weight");
return true;
case R.id.loose_weight:
//act for menu_item1
category.setText("Loose Weight");
return true;
case R.id. gain_weight:
//act for sub_menu_item1
category.setText("Gain Weight");
return true;
case R.id. build_muscle:
//act for sub_menu_item1
category.setText("Build Muscle");
return true;
case R.id. run:
//act for sub_menu_item1
category.setText("Run");
return true;
case R.id. walk:
//act for sub_menu_item1
category.setText("Walk");
return true;
default:
//pass the event to parent, for options menu, use below
}
return false;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}
private void gender_button()
{
gender.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ProfilePage.this, gender);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.gender_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id. male:
//act for menu_item1
gender.setText("Male");
return true;
case R.id. female:
//act for sub_menu_item1
gender.setText("Female");
return true;
default:
//pass the event to parent, for options menu, use below
}
return false;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}
private void small_banner_ad()
{
AdView adView = (AdView) this.findViewById(R.id.adView);
//request TEST ads to avoid being disabled for clicking your own ads
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)// This is for emulators
//test mode on DEVICE (this example code must be replaced with your device uniquq ID)
.addTestDevice("15174709D5FCBF710958952E2589F20D") // Nexus 6
.build();
adView.loadAd(adRequest);
}
private void save_update_button()
{
ParseUser.getCurrentUser();
ParseQuery<ParseObject> pQuery = new ParseQuery<ParseObject>("profile_info");
pQuery.whereEqualTo("user_name", userName.getText().toString());
pQuery.getFirstInBackground(new GetCallback<ParseObject>()
{ [user=439709]@override[/user]
public void done(ParseObject update, ParseException e) {
if (e == null){
update.put("user_name", userName.getText().toString());
update.put("first_name", fname.getText().toString());
update.put("last_name", lname.getText().toString());
update.put("height_in_feet", hf.getText().toString());
update.put("height_in_inches", hi.getText().toString());
update.put("weight", weight.getText().toString());
update.put("waist", waist.getText().toString());
update.put("wrist", wrist.getText().toString());
update.put("hip", hip.getText().toString());
update.put("forearm", forearm.getText().toString());
update.put("age", age.getText().toString());
update.put("gender", gender.getText().toString());
update.put("category", category.getText().toString());
update.put("unit", unit.getText().toString());
update.put("goal", goal.getText().toString());
update.saveInBackground();
Toast.makeText(getApplicationContext(),
"Your profile has been updated",
Toast.LENGTH_SHORT)
.show();
} else {
final ParseObject profile_info = new ParseObject("profile_info");
profile_info.put("user_name", userNameTxt);
profile_info.put("first_name", fname.getText().toString());
profile_info.put("last_name", lname.getText().toString());
profile_info.put("height_in_feet", hf.getText().toString());
profile_info.put("height_in_inches", hi.getText().toString());
profile_info.put("weight", weight.getText().toString());
profile_info.put("waist", waist.getText().toString());
profile_info.put("wrist", wrist.getText().toString());
profile_info.put("hip", hip.getText().toString());
profile_info.put("forearm", forearm.getText().toString());
profile_info.put("age", age.getText().toString());
profile_info.put("gender", gender.getText().toString());
profile_info.put("category", category.getText().toString());
profile_info.put("unit", unit.getText().toString());
profile_info.put("goal", goal.getText().toString());
// Create an user data relationship with the current user
profile_info.put("user_data", ParseUser.getCurrentUser());
// Save the post and return
profile_info.saveInBackground(new SaveCallback () {
[user=439709]@override[/user]
public void done(ParseException e) {
if (e == null) {
setResult(RESULT_OK);
Toast.makeText(getApplicationContext(),"Profile saved",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}});
}
}
});
}
//image button
public void image_button(){
image.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// Create the Intent for Image Gallery.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}});
}
//menu [user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.profile_menu, menu);
return super.onCreateOptionsMenu(menu);
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
// Handle action buttons
switch(item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.logout:
ParseUser.logOut();
finish();
return true;
case R.id.Wall:
Intent intent = new Intent(ProfilePage.this,
Wall.class);
startActivity(intent);
return true;
case R.id.Save:
save_update_button();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
[user=439709]@override[/user]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}}}
[\CODE]
When I import "uri" for my on activity results at the end of my code I get a bunch of errors for everything I'm doing with parse. I been searching and trying different image picker tutorials and always end up with same results. I've checked out parse.com but only see info on saving images from the drawable folder. If I can get the image picker to work I'm pretty sure I can figure out how to save it to parse.com.
Sent from my Nexus 6 using XDA Free mobile app

Categories

Resources