I am new to Android developer. I have 2 different class (MainActivity.java & Upload.java)
I have problem to call Upload.java into Main.Activity.
When I click the button, the app is crashing.
Is there anything that I have done wrong?
MainActivity.java
Button upload = (Button)findViewById(R.id.upload_Btn);
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Update_Table dbClient = new Update_Table();
try {
dbClient.DynamoDBClient();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("sys", "Success");
}
}
}
Upload.java
public class Update_Table
{
private String tableName = "Test";
private AmazonDynamoDBClient client =null;
public void DynamoDBClient() throws IOException
{
AWSCredentials cred = new PropertiesCredentials(Update_Table.class
.getResourceAsStream("AwsCredentials.properties"));
client = new AmazonDynamoDBClient(cred);
}
}
LOGCAT:
Change the line in the method like below:-
public class Update_Table
{
private String tableName = "Test";
private AmazonDynamoDBClient client =null;
public void DynamoDBClient() throws IOException
{
//changed the below line
AWSCredentials cred = new PropertiesCredentials(ClassLoader.getResourceAsStream("src/com.afdal.ftsmetheses/AwsCredentials.properties"));
//OR try this
AWSCredentials cred = new PropertiesCredentials(ClassLoader.getResourceAsStream("com.afdal.ftsmetheses/AwsCredentials.properties"));
client = new AmazonDynamoDBClient(cred);
}
}
Related
A NullPointerException occurs on the indicated line of my endpoint api method when called by the android client but not when called from the api explorer:
#ApiMethod(name = "publishReview", path = "publish-review", httpMethod = ApiMethod.HttpMethod.POST)
public Review publishReview(#Named("userId") final String id, ReviewForm reviewForm) {
Key<Profile> profileKey = Key.create(Profile.class, id);
final Key<Review> reviewKey = factory().allocateId(profileKey, Review.class);
final Long reviewId = reviewKey.getId();
Profile user = ofy().load().key(profileKey).now();
Review review = new Review(reviewId, id, reviewForm);
user.addToMyReviews(reviewId); // NULLPOINTER HERE
ofy().save().entities(review, user).now();
return review;
}
Here is addToMyReviews(Long reviewId):
public void addToMyReviews(final Long reviewId) {
if (!myReviews.contains(reviewId))
myReviews.add(reviewId);
}
Here is the android client side call of the endpoint method:
public static class PublishReview extends AsyncTask<Void, Void, String> {
private static MyApi myApiService = null;
private ReviewForm mReview;
private final String mUserId;
private Context mContext;
public PublishReview(final String userId, ReviewForm review, Context context) {
mReview = review;
mUserId = userId;
mContext = context;
}
#Override
protected String doInBackground(Void... params) {
if (myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
myApiService = builder.build();
}
try {
return myApiService.publishReview(mUserId, mReview).execute().getTitle();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String title) {
Toast.makeText(mContext, title + " published", Toast.LENGTH_LONG).show();
}
}
The mUserId and mReview variables on the client side are not null when passed into the endpoint method as params.
How do I fix this error?
I know its a common error , and i know lots of topics here were asking about the same error, but i tried alot of solutions and non works.
My application is like this:
1st activity is a sign in activity,
2nd is a menu to navigate where to go,
3rd is the customer's details.
I think i know where the problem is but i don't whats causing it
In the 2nd activity i am calling a function to get the customer id (the same function i am calling in the 3rd activity but without taking all the details i am only taking it's ID because i need it in other activities )
So result i am getting second time is always null , which is causing this error
so if i jump directly from 1st to 3rd app doesn't crash.
but (1st 2nd 3rd ) then the function will be called twice (even though i am storing data in a different object) and works only at the first time it's called
Hope i explained it well
now my code for 2nd activity:
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncpkAbone().execute(SharedValues.AboneKod);
setContentView(R.layout.activity_after_login);
}
public void AboneBilgiPressed(View v){
Intent i = new Intent(AfterLogin.this, UserDetailsActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
protected class AsyncpkAbone extends AsyncTask<String,Void,UserDetailsTable>
{
#Override
protected UserDetailsTable doInBackground(String... params) {
// TODO Auto-generated method stub
UserDetailsTable userDetail2=null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetUserDetails(params[0]);
JSONParser parser = new JSONParser();
userDetail2 = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail2;
}
#Override
protected void onPostExecute(UserDetailsTable result2) {
// TODO Auto-generated method stub
SharedValues.AboneKod =result2.getAboneKod();
SharedValues.pkAbone = result2.getPkAbone();
}
}
the Code for the 3rd activity (user details)
public class UserDetailsActivity extends AppCompatActivity {
TextView tvAdres, tvTelefon,tvpkAbone;
String Adres;
String WEBParola;
String Tel1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
new AsyncUserDetails().execute(SharedValues.AboneKod);
tvAdres = (TextView) findViewById(R.id.tv_firstname);
tvAdres.setTextIsSelectable(true);
tvTelefon = (TextView) findViewById(R.id.tv_lastname);
tvTelefon.setTextIsSelectable(true);
tvpkAbone = (TextView) findViewById(R.id.tv_pkAbone);
tvpkAbone.setTextIsSelectable(true);
tvAdres.setText(Adres);
tvTelefon.setText(Tel1);
tvpkAbone.setText(String.valueOf( SharedValues.pkAbone));
}
protected class AsyncUserDetails extends AsyncTask<String,Void,UserDetailsTable>
{
#Override
protected UserDetailsTable doInBackground(String... params) {
// TODO Auto-generated method stub
UserDetailsTable userDetail=null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetUserDetails(params[0]);
JSONParser parser = new JSONParser();
userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail;
}
#Override
protected void onPostExecute(UserDetailsTable result) {
// TODO Auto-generated method stub
tvAdres.setText(result.getAdres());
tvTelefon.setText(result.getTelefon());
}
}
the data i get from the function is stored in a object of type (userdetails tables)
the code for the Userdetailstable is (might be needed)
package com.artyazilim.art;
public class UserDetailsTable {
String Adres,Tel1,AboneKod,WEBParola;
int pkAbone;
public UserDetailsTable(String Adres, String Tel1, String AboneKod,
String WEBParola,int pkAbone) {
super();
this.Adres = Adres;
this.Tel1 = Tel1;
this.AboneKod = AboneKod;
this.WEBParola = WEBParola;
this.pkAbone = pkAbone;
}
public UserDetailsTable() {
super();
this.Adres = null;
this.Tel1 = null;
this.AboneKod = null;
this.WEBParola = null;
this.pkAbone = 0;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
Adres = adres;
}
public String getTelefon() {
return Tel1;
}
public void setTelefon(String telefon) {
Tel1 = telefon;
}
public String getAboneKod() {
return AboneKod;
}
public void setAboneKod(String aboneKod) {
AboneKod = aboneKod;
}
public String getWEBParola() {
return WEBParola;
}
public void setWEBParola(String WEBParola) {
this.WEBParola = WEBParola;
}
public int getPkAbone() {
return pkAbone;
}
public void setPkAbone(int pkAbone) {
this.pkAbone = pkAbone;
}
}
the function which i am calling in the both Async is this:
public JSONObject GetUserDetails(String AboneKod) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","Service1");
o.put("method", "GetUserDetails");
p.put("AboneKod",mapObject(AboneKod));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
and in the web service this is the GetUserDetails function:
public DataTable GetUserDetails(string AboneKod)
{
DataTable userDetailsTable = new DataTable();
userDetailsTable.Columns.Add(new DataColumn("Adres", typeof(String)));
userDetailsTable.Columns.Add(new DataColumn("Tel1", typeof(String)));
userDetailsTable.Columns.Add(new DataColumn("pkAbone", typeof(String)));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT Adres,Tel1,pkAbone FROM r_Abone WHERE AboneKod='" + AboneKod + "';";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
userDetailsTable.Rows.Add(reader["Adres"], reader["Tel1"], reader["pkAbone"]);
}
}
reader.Close();
dbConnection.Close();
return userDetailsTable;
}
the error i am getting when going from 2nd to 3rd is
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.artyazilim.art.UserDetailsTable.getAdres()' on a
null object reference
10-30 05:33:13.410 24881-24881/com.artyazilim.art E/AndroidRuntime:
at
com.artyazilim.art.UserDetailsActivity$AsyncUserDetails.onPostExecute(UserDetailsActivity.java:74)
10-30 05:33:13.410 24881-24881/com.artyazilim.art E/AndroidRuntime:
at
com.artyazilim.art.UserDetailsActivity$AsyncUserDetails.onPostExecute(UserDetailsActivity.java:47)
10
i know it seems like a duplicate and I know the rules search before ask,I have spent lots of time trying other's solutions but the reason i might didn't find the answer else where is because i don't know whats is actually causing this error so not knowing what to search for.
thanks in advance :)
In you second activity check if result2.getAboneKod(); is not returning a null object.
I think this is why when you open the 3rd activity from the 2nd, you have the NullPointerException.
I have been trying for a few days to do Simple User Authentication with Java (not Android) and Firebase. Before I started out with Firebase's user authentication classes I tried using Java to do a simple save and retrieve on my Firebase Reference with no success. No errors are reported but nothing happens in Firebase (no changes to the data). In the past, I have been able to integrate Firebase with Android SDK with no issues. I am making use of Firebase JAR for JVM but nothing is happening.
import com.firebase.client.AuthData;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
/**
*
* #author Chidi
*/
public class Auth {
private final Firebase usersRef;
private boolean isNewUser = false;
private String uid = null;
private HashMap<String, Object> userHash;
public Auth() {
Firebase rootRef = new Firebase("https://tranzchat.firebaseio.com/");
this.usersRef = rootRef.child("users");
userHash = new HashMap<>();
}
public void createUser(final String email, final String password, String name, String default_lang) {
userHash.put("email", email);
userHash.put("password", this.hashPassword(password));
userHash.put("name", name);
userHash.put("default_lang", default_lang);
Vars.dbcon.createUser(email, password, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
System.out.println("Created the new user");
// Sets isNewUser to true after creating the new user
isNewUser = true;
signIn(email, password);
if(uid != null) {
// Try to store use information
Firebase newUserRef = usersRef.child(uid);
newUserRef.setValue(userHash, new Firebase.CompletionListener(){
#Override
public void onComplete(FirebaseError fe, Firebase frbs) {
System.out.println("Completed Database Insertion");
}
});
} else {
System.out.println("Could not retrieve UID");
}
}
#Override
public void onError(FirebaseError fe) {
System.out.println("An error occured while creating the user.");
}
});
}
public void signIn(String email, String password) {
Vars.dbcon.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
uid = authData.getUid();
if(!isNewUser) {
// Try to get new user information and store it in the user object
usersRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
userHash = (HashMap<String, Object>) snapshot.getValue();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
}
});
}
public String hashPassword(String password) {
String md5 = null;
if(password == null) return null;
try {
// Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
// Update input string in message digest
digest.update(password.getBytes(), 0, password.length());
// Converts message digest value in base 16 (hex)
md5 = new BigInteger(1, digest.digest()).toString();
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5;
}
// Test Suite
public static void main(String[] args) throws InterruptedException {
Vars.init();
Thread firebaseAuth = new Thread(new Runnable() {
#Override
public void run() {
Auth au = new Auth();
au.createUser("chidiebere.nnadi#gmail.com", "password", "Chidiebere Nnadi", "en");
}
});
firebaseAuth.start();
firebaseAuth.join();
}
}
I just found out the issue with it. The thread was ending before Firebase could call the onComplete function. You can just call a Thread.sleep(x_ms) within a loop after the last line of code in the application.
I'm going to upload multiple photo/video using LoopJ AndroidAsyncHttp to server. My problem is i need to add cancel button for each of the photo and allow the user to cancel the uploading. May i know anyone got the solution for this? or any others better example for me to refer?
My Code as below :-
public static void putMultipleUploadPhoto(String server,
final ProgressBar progressbarb, final String FileType, final TextView textviewb, final String FolderPath, final int itemcount, final int position)
{
final String url = "http://" + server + ":" + server.Photo_Upload;
File myFile = new File(data);
final RequestParams params = new RequestParams();
try {
params.put("data", myFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final AsyncHttpClient client = new AsyncHttpClient();
final int totalprogress1 = 0;
try {
client.post(url,params,new AsyncHttpResponseHandler() {
public void onStart() {
// Initiated the request
progressbarb.setProgress(0);
}
#Override
public void onProgress(int position, int length) {
// TODO Auto-generated method stub
int totalprogress;
totalprogress = (position*100)/length;
progressbarb.setProgress(totalprogress);
super.onProgress(position, length);
}
#Override
public void onSuccess(String response) {
String regex = "\n"; // Only this line is changed.
String split[] = response.split(regex, 2);
if (split[0] != null)
{
String status[]=split[0].split("\\t");
if (status[0].equals("true"))
{
textviewb.setVisibility(View.VISIBLE);
textviewb.setText("Success");
if (status[0].equals("false"))
{
textviewb.setText("Fail";
textviewb.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onFailure(Throwable e, String response) {
textviewb.setVisibility(View.VISIBLE);
textviewb.setText("Fail");
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Very simple dear-
1)just send one by one image on server and then create a popup window for send next image or cancel.
2)In your database or where you have images just set flag 0 and 1. So you can easily make query
for send image on server which one is pending.
3)And when you got successes response from server change your flag value in database.
My story file:
Narrative:
In order to document all the business logic requests
As a user
I want to work with documents
Scenario: Basic new document creation
Given a user name Micky Mouse
When new document created
Then the document should named new document
And the document status should be NEW
My code:
public class DocStories extends JUnitStory {
#Override
public Configuration configuration() {
return new MostUsefulConfiguration().useStoryLoader(
new LoadFromClasspath(getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder().withFormats(Format.STATS,
Format.HTML, Format.CONSOLE, Format.TXT));
}
#Override
public List<CandidateSteps> candidateSteps() {
return new InstanceStepsFactory(configuration(), new DocSteps())
.createCandidateSteps();
}
#Override
#Test
public void run() throws Throwable {
try {
super.run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In the class with my steps:
public class DocSteps {
private final Map<String, User> users = new HashMap<String, User>();
private final DocManager manager = new DocManager();
private User activeUser;
private Document activeDocument;
private boolean approvedResult;
*****************BEFORE***************//
#BeforeStories
private void initUsers() {
users.put("Micky Mouse", new User("Micky Mouse", UserRole.ANALYST));
users.put("Donald Duck", new User("Donald Duck", UserRole.BCR_LEADER));
System.out.println("Check this out" + users.toString());
}
// **********steps*************//
#Given("a user name $userName")
public void connectUser(String userName) {
// in the real world - it will get the user from the db
System.out.println(userName);
activeUser = new User(userName, UserRole.ANALYST);
// System.out.println(activeDocument.getName());
}
#Given("a new document")
#When("new document created")
public void createDocument() {
activeDocument = new Document();
}
#Given("a document with content")
public void createDocWithContect() {
createDocument();
activeDocument.setContent("this is a document");
}
#Then("the document should named $docName")
#Alias("the document name should be $docName")
public void documentNameShouldBe(String docName) {
Assert.assertEquals(docName, activeDocument.getName());
}
#Then("the document status should be $status")
public void documentStatusShouldBe(String status) {
DocStatus docStatus = DocStatus.valueOf(status);
Assert.assertThat(activeDocument.getStatus(),
Matchers.equalTo(docStatus));
}
// *****************AFTER***************//
#AfterScenario
public void clean() {
activeUser = null;
activeDocument = null;
approvedResult = false;
}
}
The methods with the "before and after" stories annotation are not executed.
the enum converter doesn't work as well.
What is wrong with my configuration (I assume it is my configuration)?
The problem is that your method initUsers is private. Just make it public and it will be visible to JBehave engine:
#BeforeStories
public void initUsers() {
//...
}