Unable to solve error - javax.mail.authenticationfailedexception: [EOF] - javascript

I have created an application where it scans bar codes and QR codes on the phone and send an email of the collected data to my personal email which is a gmail. However, recently it stopped sending emails and prompted me an error as shown below:
javax.mail.authenticationfailedexception: [EOF]
NOTE: I am relatively new at this
I have been told to change it from SMTP to SSL but I cant seem to fix the issue.
package com.example.createexcelsample;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.nio.charset.Charset;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import static android.content.ContentValues.TAG;
public class SendMail extends AsyncTask<Void, Void, Void> {
private Context context;
private Session session;
private String email;
private String subject;
private String message;
private String fileName;
private MyWebServiceResult listener;
public String SendError = "";
private ProgressDialog progressDialog;
private String email_uid = "EMAIL";//Email written here
private String email_pwd = "123456";
/*URL url = new URL("https://office365.com");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
//copyInputStreamToOutputStream(in, System.out);*/
public interface MyWebServiceResult {
public void onSendIsComplete();
public void onSendError(String Error);
}
public void setWebServiceResult(MyWebServiceResult listener) {
this.listener = listener;
}
public SendMail(Context context, String email, String subject, String message,String fileName,String email_uid, String email_pwd){
//this.email_uid = email_uid;
//this.email_pwd = email_pwd;
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.fileName = fileName;
this.listener = null;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//props.put("mail.smtp.host", "smtp.gmail.com");
/* props.put("mail.smtp.host", "212.12.184.20");
props.put("mail.smtp.port", "110");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");*/
//props.put("mail.smtp.ssl.trust", "212.12.184.20");
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email_uid, email_pwd);
}
});
try {
MimeMessage mm = new MimeMessage(session);
mm.setFrom(new InternetAddress(email_uid));
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
mm.setSubject(subject);
mm.setText("body");
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
mm.setContent(multipart);
SendError = "";
Transport.send(mm);
}
catch (MessagingException e) {
SendError = e.toString().toString();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// progressDialog.dismiss();
if (SendError.toString().isEmpty()){
listener.onSendIsComplete();
} else {
listener.onSendError(SendError);
}
}
/* public void hideSoftKeyboard(AutoProgramingValid activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
AutoProgramingValid.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}*/
}

Related

Problem with user registration through Firebase - not saving data in Realtime Database‏

I'm developing a social networking app that uses subscribing and building a user profile through FareBas.
Unfortunately, the program works and when the user presses the register button, an error appears and the information does not go into real-time.
!I would be very grateful for the help.
Registration page:
package com.example.myapplicationfire;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Patterns;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class reg extends AppCompatActivity implements View.OnClickListener
{
EditText name, pass, email, bio;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
Button b,b1;
ProgressDialog p;
DatabaseReference myref = firebaseDatabase.getReference("Users");
ImageView pic;
Uri uri;
StorageReference storageReference;
String picName;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
name = findViewById(R.id.et1);
pass = findViewById(R.id.et2);
email = findViewById(R.id.et3);
bio = findViewById(R.id.et5);
b = findViewById(R.id.b1);
b.setOnClickListener(this);
b1 = findViewById(R.id.b2);
b1.setOnClickListener(this);
pic =findViewById(R.id.pic1);
pic.setImageResource(R.drawable.person);
pic.setOnClickListener(this);
sp=getSharedPreferences("details",0);
firebaseAuth = FirebaseAuth.getInstance();
}
public void createUser() {
p = new ProgressDialog(this);
p.setMessage("Registration...");
p.show();
if (isValidate())
firebaseAuth.createUserWithEmailAndPassword(email.getText().toString
(), pass.getText().toString()).addOnCompleteListener(this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull
Task<AuthResult> task) {
if (task.isSuccessful()) {
storageReference =
FirebaseStorage.getInstance().getReference("Image/Users/"+email.getText().toString().replace('.',' '));
storageReference = storageReference.child(picName);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener <UploadTask.TaskSnapshot>() {
#Override
public void
onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(reg.this, "תמונה הועלתה", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(reg.this, "" +
e.getMessage(), Toast.LENGTH_LONG).show(); }
});
myref=firebaseDatabase.getReference("users").push();
User u = new
User(name.getText().toString(), pass.getText().toString(),
email.getText().toString(), myref.getKey(),picName,bio.getText().toString());
myref.setValue(u);
p.dismiss();
Toast.makeText(reg.this, "ההרשמה הצליחה!", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(reg.this,
"" + e.getMessage(), Toast.LENGTH_LONG).show();
p.dismiss();
}
});
}
public boolean isValidate() {
if (!
Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches()) {
email.setError("Invalid email");
email.setFocusable(true);
return false;
} else if (pass.getText().toString().length() < 6) {
pass.setError("password length at least 6 characters");
pass.setFocusable(true);
return false;
}
else if (bio.getText().toString().length() < 10) {
bio.setError("bio length should be 10-100 characters");
bio.setFocusable(true);
return false;
}
return true;
}
#Override
public void onClick(View view) {
if (view == pic) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
}
if (view == b) {
createUser();
if(isValidate()){
sp=getSharedPreferences("details",0);
SharedPreferences.Editor editor=sp.edit();
editor.putBoolean("isChecked",true);
editor.putString("name",name.getText().toString());
editor.putString("bio",bio.getText().toString());
editor.putString("email",email.getText().toString());
editor.commit();
Intent intent = new Intent(reg.this, homepage.class);
intent.putExtra("email", email.getText().toString());
startActivity(intent);
}
}
if(view==b1){
Intent intent = new Intent(reg.this, login.class);
startActivity(intent);
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && requestCode == 0 && data.getData() != null) {
uri = data.getData();
if (uri != null) {
pic.setImageURI(uri);
picName = System.currentTimeMillis() + "." + getFileExtension(uri);
}
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public void ShowHidePass(View view) {
if (view.getId() == R.id.show_pass_btn) {
if (pass.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())) {
((ImageView) (view)).setImageResource(R.drawable.showeye1);
//Show Password
pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
((ImageView) (view)).setImageResource(R.drawable.showeye);
//Hide Password
pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
}}
Error:
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.

Call php script inside java activity after click

I am parsing a JSON title, URL etc. from a PHP script. I want to give a reward with PHP script after the user click my link. Reward code -
String awr = Config.Base_Url+"videos/award.php";
Now everything is working, there is just no reward, no call to my PHP script...
How do i need modify my script to get correct reward? My java activity -
package com.uabclousy.pjanidemo;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.uabclousy.pjanidemo.app.App;
import com.uabclousy.pjanidemo.constants.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.content.Intent;
public class ItemsActivity extends BaseActivity {
private PrefManager prf;
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "https://pjani.com/ImageJsonData.php";
String Image_Name_JSON = "image_title";
String Image_Decription_JSON = "app_description";
String Image_URL_JSON = "image_url";
String App_URL_JSON = "app_url";
String App_Message_JSON = "app_message";
String App_Points = "app_points";
String App_Id = "videoId";
String App_sec = "id";
public static final String EXTRA_VIDEO_ID = "id";
public static final String EXTRA_ID = "id";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
ArrayList<String> AppmessageArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items);
prf = new PrefManager(this);
getSupportActionBar().setIcon(R.drawable.ic_back_icon);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ImageTitleNameArrayListForClick = new ArrayList<>();
AppmessageArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
validate();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(ItemsActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(ItemsActivity.this, AppmessageArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
String url = ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition);
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra("points", App_Points);
intent.putExtra("vid", App_Id);
intent.putExtra("id", App_sec);
intent.putExtra("yourreq4", "fuck13");
setResult(RESULT_OK, intent);
finish();
startActivity(intent);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
void award_items(final String points, final String tostore, final String type){
String awr = Config.Base_Url+"videos/award.php";
final String v1 ="1";
final String v0 ="0";
final String v2 ="2";
StringRequest stringRequest = new StringRequest(Request.Method.POST, awr,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Enable this only on testing - yash
//Toast.makeText(VideosActivity.this, response, Toast.LENGTH_LONG).show();
if(response.intern() == v1.intern()) {
Toast.makeText(ItemsActivity.this, points+" "+getString(R.string.points_received), Toast.LENGTH_SHORT).show();
prf.setBoolean(tostore, true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
if(response.intern() == v0.intern()) {
Toast.makeText(ItemsActivity.this, getString(R.string.already_watched), Toast.LENGTH_SHORT).show();
prf.setBoolean(tostore, true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
if(response.intern() == v2.intern()){
Toast.makeText(ItemsActivity.this,getString(R.string.server_problem),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ItemsActivity.this,getString(R.string.server_problem),Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", App.getInstance().getUsername());
params.put("points",App_Points);
params.put("type",type);
params.put("videoid",Image_Name_JSON);
params.put("date","hehe");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_about, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case R.id.share:
shareURL();
return true;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
// sharing
void shareURL() {
try
{ Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
String sAux = getString(R.string.share_text)+"\n";
sAux = sAux + "https://play.google.com/store/apps/details?id="+getApplicationContext().getPackageName()+"\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, getString(R.string.choose_one)));
}
catch(Exception e)
{ //e.toString();
}
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(ItemsActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageDescription(json.getString(Image_Decription_JSON));
// Opening link in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(App_URL_JSON));
// Adding message in array to display on RecyclerView click event.
AppmessageArrayListForClick.add(json.getString(App_Message_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setAppPoints(json.getString(App_Points));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
void validate(){
if (Config.Base_Url.intern() == Constants.API_License && !BuildConfig.DEBUG && Constants.release) {
App.getInstance().logout();
Intent i = new Intent(getApplicationContext(), AppActivity.class);
startActivity(i);
finish();
ActivityCompat.finishAffinity(ItemsActivity.this);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
award_items(data.getStringExtra("points"),data.getStringExtra("id"),getString(R.string.webpanel_credit));
// Toast.makeText(getApplicationContext(), data.getStringExtra("id"), Toast.LENGTH_SHORT).show();
}
}
}
}
Thank you very much for helping!

How to start New Layout (activity) from ListView

When I click the ListView, I'd like to start a new Activity
Here is my MainActivity.java
package com.theheran.listviewicon;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
//Declarasi Array Menu dan gambar
ListView list;
String[] menu = {
"#The_Heran",
"www.theheran.com",
"Add",
"Delete",
"Next",
"Back",
"Find",
"Warning"
} ;
Integer[] imageId = {
R.drawable.ic_launcher,
R.drawable.signal,
R.drawable.add,
R.drawable.trash,
R.drawable.next,
R.drawable.back,
R.drawable.find,
R.drawable.warning
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomListView adapter = new
CustomListView(MainActivity.this, menu, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +menu[+ position], Toast.LENGTH_SHORT).show();
// HERE THE PROBLEM (Intent)
Intent intent = new CustomListView(MainActivity.this,);
startActivity(intent);
}
});
}
}
My CustomListView
package com.theheran.listviewicon;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomListView extends ArrayAdapter<String> {
//Declarasi
private final Activity context;
private final String[] web;
private final Integer[] imageId;
public CustomListView(Activity context,String[] web, Integer[] imageId) {
super(context, R.layout.list_single_data, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
//Load Custom Layout untuk list
View rowView= inflater.inflate(R.layout.list_single_data, null, true);
//Declarasi komponen
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtList);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgIcon);
//Set Parameter Value
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
// HERE THE PROBLEM (Intent)
Intent intent = new CustomListView(MainActivity.this,);
startActivity(intent);
Here you are trying to use a wrong structure.
Use this:
Intent intent = new Intent(MainActivity.this, NextActivity.class);
MainActivity.this.startActivity(intent );
Try this way ,
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +position , Toast.LENGTH_SHORT).show();
Intent MoveToNext = new Intent(getApplicationContext(), Your_Next_Activity.class);
startActivity(MoveToNext);
}
});
This is how I have done it. You start a new activity using the startActivityForResult(intent, 2); Where you throw a intent and a number (number that you check for when you go back to the starting page).
private void registerButtonClickList() {
ListView list = (ListView) findViewById(R.id.listView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(InThisClass.this, GoingToThisClass.class);
intent.putExtra("Position", position);
startActivityForResult(intent, 0);
}
});
}
Use this where in the same class as you started the other one form the list. This is needed since you are expecting a return when you start with startActivityForResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
//See what u should do using the requestCode
//and check if it ended OK
}
if (resultCode == Activity.RESULT_CANCELED) {
//what you do when canceled
}
}
}
And in the activity that you started you need to end with this because you are expected to return something. This you do by using setResult().
Button btn = (Button) findViewById(R.id.btn);
btnCANCEL.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View v) {
Intent intent = new Intent();
setResult(Activity.RESULT_OK, intent);
//intent.putExtra("something", something); if you need to send something back
finish();
}
});
Hope this helps!

Titanium Push Notification AeroGear

Im trying to send notifications to a Titanium App from AeroGear. After getting the token, how can subscribe to the channel?
Obteining the token:
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
CloudPush.addEventListener('callback', function (evt) {
alert("Notification received: " + evt.payload);
});
This is the example code for native Androiod:
package com.push.pushapplication;
import java.net.URI;
import java.net.URISyntaxException;
import org.jboss.aerogear.android.unifiedpush.PushConfig;
import org.jboss.aerogear.android.unifiedpush.PushRegistrar;
import org.jboss.aerogear.android.unifiedpush.Registrations;
import android.app.Application;
public class PushApplication extends Application {
private final String VARIANT_ID = "variant_id";
private final String SECRET = "secret";
private final String GCM_SENDER_ID = "1";
private final String UNIFIED_PUSH_URL = "URL";
private PushRegistrar registration;
#Override
public void onCreate() {
super.onCreate();
Registrations registrations = new Registrations();
try {
PushConfig config = new PushConfig(new URI(UNIFIED_PUSH_URL), GCM_SENDER_ID);
config.setVariantID(VARIANT_ID);
config.setSecret(SECRET);
config.setAlias(MY_ALIAS);
registration = registrations.push("unifiedpush", config);
registration.register(getApplicationContext(), new Callback() {
private static final long serialVersionUID = 1L;
#Override
public void onSuccess(Void ignore) {
Toast.makeText(MainActivity.this, "Registration Succeeded!",
Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Exception exception) {
Log.e("MainActivity", exception.getMessage(), exception);
}
});
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
Really lost here, any help would be appreciated!
You need to make wrapper around AeroGear native library as titanium module. However, it may be difficult if you didn't it before.
The titanium module that you need to get this working has been made by "Mads" and you can find it here: https://github.com/Napp/AeroGear-Push-Titanium

convert activity into fragment that can call activity

i have problem to convert activity to fragment, but function of "getBaseContext" and "this" can't work
package prj.apdev.c17;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DataBase extends Fragment {
TempatDatabase dm;
EditText inama, idosis, ilabel;
Button btambah;
TableLayout tabel4data;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View va = inflater.inflate(R.layout.mapping_fragment, container, false);
return va;
dm = new TempatDatabase(this);
tabel4data = (TableLayout) va.findViewById (R.id.tabel_data);
inama = (EditText) va.findViewById(R.id.dose_nama_e);
idosis = (EditText) va.findViewById(R.id.dose_dosis_e);
ilabel = (EditText) va.findViewById(R.id.dose_label_e);
btambah = (Button) va.findViewById(R.id.button_add);
btambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
simpanData();
}
});
updateTable();
}
private void updateTable() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
while (tabel4data.getChildCount() > 1) {
tabel4data.removeViewAt(1);
}
double aa = tabel4data.getChildCount();
String a = String.valueOf(aa);
Toast.makeText(getBaseContext(), "tabel data child : " + a,
Toast.LENGTH_SHORT).show();
ArrayList<ArrayList<Object>> data = dm.ambilSemuaBaris();//
for (int posisi = 0; posisi < data.size(); posisi++) {
TableRow tabelBaris = new TableRow(this);
ArrayList<Object> baris = data.get(posisi);
TextView idTxt = new TextView(this);
idTxt.setText(baris.get(0).toString());
tabelBaris.addView(idTxt);
TextView namaTxt = new TextView(this);
namaTxt.setText(baris.get(1).toString());
tabelBaris.addView(namaTxt);
TextView dosisTxt = new TextView(this);
dosisTxt.setText(baris.get(2).toString());
tabelBaris.addView(dosisTxt);
TextView labelTxt = new TextView(this);
labelTxt.setText(baris.get(3).toString());
tabelBaris.addView(labelTxt);
tabel4data.addView(tabelBaris);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void simpanData() {
// TODO Auto-generated method stub
try {
dm.addRow(inama.getText().toString(), idosis.getText().toString(), ilabel.getText().toString());
Toast.makeText(getBaseContext(), inama.getText().toString() + ", berhasil disimpan",
Toast.LENGTH_SHORT).show();
updateTable();
kosongkanField();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getBaseContext(), "gagal simpan, " + e.toString(),
Toast.LENGTH_LONG).show();
}
}
private void kosongkanField() {
// TODO Auto-generated method stub
inama.setText("");
idosis.setText("");
ilabel.setText("");
}
}
and this my database class
package prj.apdev.c17;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class TempatDatabase {
private static final String ROW_ID = "_id";
private static final String ROW_NAMA = "nama";
private static final String ROW_DOSIS = "dosis";
private static final String ROW_LABEL = "label";
private static final String NAMA_DB ="APdev";
private static final String NAMA_TABEL="Doseme";
private static final int DB_VERSION=1;
private static final String CREATE_TABLE =
"create table "+NAMA_TABEL+" ("+ROW_ID+" integer PRIMARY KEY autoincrement, "+ROW_NAMA+" text,"+ROW_DOSIS+" text, "+ROW_LABEL+" text)";
//membuat mendeklarasikan itu adalah context
private final Context context;
//membuat mendeklarasikan DatabaseOpenHelper itu adalah dbhelper
private DatabaseOpenHelper dbhelper;
//membuat mendeklarasikan SQLiteDatabase itu adalah db
private SQLiteDatabase db;
//mengambil context untuk mengakses system di android
public TempatDatabase(DataBase ctx) {
//mendeklarasikan ctx adalah context ( context context di ganti ctx )
this.context = ctx;
// membuat DatabaseOpenHelper
dbhelper = new DatabaseOpenHelper(context);
//menuliskan DatabaseOpenHelper = SQLiteDatabase
db = dbhelper.getWritableDatabase();
}
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
//membuat database
public DatabaseOpenHelper(Context context) {
super(context, NAMA_DB, null, DB_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
//memperbarui database bila sudah ada
#Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+NAMA_DB);
onCreate(db);
}
}
//menutup DatabaseOpenHelper
public void close() {
dbhelper.close();
}
//menambahkan pada row
public void addRow(String nama, String dosis, String label) {
ContentValues values = new ContentValues();
values.put(ROW_NAMA, nama);
values.put(ROW_DOSIS, dosis);
values.put(ROW_LABEL, label);
try {
//menambahkan nama tabel bila tidak akan error
// db.delete(NAMA_TABEL, null, null);
db.insert(NAMA_TABEL, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
//membuat array pada table layout
public ArrayList<ArrayList<Object>> ambilSemuaBaris() {
ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try {
cur = db.query(NAMA_TABEL,
new String[] { ROW_ID, ROW_NAMA, ROW_DOSIS, ROW_LABEL }, null, null,
null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataList.add(cur.getString(3));
dataArray.add(dataList);
} while (cur.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("DEBE ERROR", e.toString());
}
return dataArray;
}
}
or if you have any method for complete this condition, you can include it.
Thanks
You can use getActivity().getBaseContext, which returns the activity associated with a fragment.
your context type is DataBase in your TempatDatabase constructor. Change it with Context i.e
public TempatDatabase(Context ctx) {
//mendeklarasikan ctx adalah context ( context context di ganti ctx )
this.context = ctx;
// membuat DatabaseOpenHelper
dbhelper = new DatabaseOpenHelper(context);
//menuliskan DatabaseOpenHelper = SQLiteDatabase
db = dbhelper.getWritableDatabase();
}
and for the fragment getActivity() method wil return the context
Problem Resolved
I've realize that function "return" must be on the end of part
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View va = inflater.inflate(R.layout.dose_fragment, container, false);
dm = new TempatDatabase(getActivity());
tabel4data = (TableLayout) va.findViewById(R.id.tabel_data);
inama = (EditText) va.findViewById(R.id.dose_nama_e);
idosis = (EditText) va.findViewById(R.id.dose_dosis_e);
ilabel = (EditText) va.findViewById(R.id.dose_label_e);
btambah = (Button) va.findViewById(R.id.button_add);
btambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
simpanData();
}
});
updateTable();
return va;
}
Thanks for helping guys.

Categories

Resources