Firebase Nullpointer exception - android

I am trying to retrieve user email from Users and then use it to get data from other firebase database nodes like the Shared_With node. But for some odd reason I am getting Null pointer exceptions. I have no idea why email is either not being retrieved or being set to null. Here is my class where I am doing all of this:
private static Context context = null;
//new name for android devices
private EditText result;
FirebaseAuth auth = FirebaseAuth.getInstance();
static SharedPreferences deviceListSharedPreferences;
//widgets
// Button btnPaired;
static ListView devicelist;
static ImageView iv;
private static DBHandler mdb;
private static Set<BluetoothDevice> pairedDevices;
String name;
static String pass;
private String mEmail;
String emaill;
String mNameRec;
String mPassRec;
String mMacRec;
private static BluetoothAdapter myBluetooth = null;
static TextView mName;
static TextView mMac;
static TextView mNameRecDev;
static TextView mMacRecDev;
private static ProgressDialog progress;
private static String address = "";
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
User userModel = new User();
private static final String TAG ="USER STATUS" ;
private OnFragmentInteractionListener mListener;
static BluetoothSocket btSocket = null;
private static boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private String encPass;
String decPass;
/*Class begins here, other methods omitted due to charectar limit*/
public main() {
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
iv = (ImageView) view.findViewById(R.id.change);
//Calling widgets
// // btnPaired = (Button) view.findViewById(R.id.button);
devicelist = (ListView) view.findViewById(R.id.listView);
mNameRecDev = (TextView)view.findViewById(R.id.nameRec);
mMacRecDev = (TextView)view.findViewById(R.id.macRec);
try {
emaill = mAuth.getCurrentUser().getEmail();
emaill = emaill.replace(".", "<");
System.out.println("Email add:" + emaill);
}catch(NullPointerException n){
System.out.println(n.getMessage());
}
if (myBluetooth.isEnabled()) { // bluetooth is connected
pairedDevicesList();
}
iv.setEnabled(false);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get the device MAC address, the last 17 chars in the View
String device_name = deviceListSharedPreferences.getString(address, mdb.getDeviceName(address));
if (v.getContentDescription().toString().equals("green")) {
iv.setImageResource(R.drawable.red);
mdb.addLog(new SimpleDateFormat("HH:mm:ss, dd/MM/yyyy").format(new Date().getTime())
+ "", MainActivity.name, MainActivity.email, device_name, "0");
iv.setContentDescription("red");
try{
sendCommand("~"+pass);
}catch(NullPointerException e){
Toast.makeText(getContext(), "Set password first", Toast.LENGTH_SHORT);
}//method to turn on
} else {
iv.setImageResource(R.drawable.green);
mdb.addLog(new SimpleDateFormat("HH:mm:ss, dd/MM/yyyy").format(new Date().getTime())
+ "", MainActivity.name, MainActivity.email, device_name, "1");
iv.setContentDescription("green");
try{
sendCommand("`"+pass);
}catch(NullPointerException e){
Toast.makeText(getContext(), "Set password first", Toast.LENGTH_SHORT);
}//method to turn off
}
}
});
System.out.println(emaill+"HEH");
DatabaseReference mdShare = FirebaseDatabase.getInstance().getReference().child("Shared_With");
mdShare.child(emaill).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mNameRec = dataSnapshot.child("Device_Name").getValue().toString();
mMacRec = dataSnapshot.child("Device_MAC").getValue().toString();
mPassRec = dataSnapshot.child("Password").getValue().toString();
decPassrd(mPassRec);
mNameRecDev.setText(mNameRec);
mMacRecDev.setText(mMacRec);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//
mNameRecDev.setOnClickListener(this);
mMacRecDev.setOnClickListener(this);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Toast.makeText(getActivity(), "Bluetooth needs to be on", Toast.LENGTH_LONG).show();
break;
// case BluetoothAdapter.STATE_TURNING_OFF:
// do something if needed
// break;
case BluetoothAdapter.STATE_ON:
// pairedDevicesList();
break;
// case BluetoothAdapter.STATE_TURNING_ON:
// do something if needed
// break;
}
}
}
};
private static class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(context, "Connecting...", "Please wait!!!"); //show a progress dialog
}
// if(iterator.getAddress().equals(DEVICE_ADDRESS)) //Replace with iterator.getName() if comparing Device names.
//
// {
//
// device=iterator; //device is an object of type BluetoothDevice
//
// found=true;
// socket = device.createRfcommSocketToServiceRecord(PORT_UUID); socket.connect();
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
// btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(UUID.fromString(dispositivo.getUuids()[0].toString()));//create a RFCOMM (SPP) connection
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
e.printStackTrace();
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(context, "Connection Failed. Are you sure the device is in range and on, or another device is not connected already?", Toast.LENGTH_LONG).show();
} else {
//Ahmed: BLUETOOTH IS CONNECTED
iv.setEnabled(true);
Toast.makeText(context, "Connected.", Toast.LENGTH_SHORT).show();
try{
sendTimedCommand("^"+pass);
}catch(NullPointerException e){
Toast.makeText(context, "Set password first", Toast.LENGTH_SHORT);
}//tell arduino device is connected //
isBtConnected = true;
}
progress.dismiss();
}
}
public static ArrayList list = new ArrayList();
public static void pairedDevicesList() {
pairedDevices = myBluetooth.getBondedDevices();
list.clear();
if (pairedDevices.size() > 0) {
for (BluetoothDevice bt : pairedDevices) { //loop
// handling custom names for devices, address => custom name
// reading already stored custom names
String customName;
// Toast.makeText(getActivity(), bt.getAddress() + " => " + bt.getName(), Toast.LENGTH_LONG).show(); //annoying
if (mdb.getDeviceName(bt.getAddress()).length() < 2) {
customName = deviceListSharedPreferences.getString(bt.getAddress(), bt.getName() + "\n" + bt.getAddress());
}
else {
customName = deviceListSharedPreferences.getString(bt.getAddress(), mdb.getDeviceName(bt.getAddress()));
}
list.add(customName); //add the appropriate name to ListView
SharedPreferences.Editor editor = listIndexToDeviceAddress.edit();
editor.putString(String.valueOf(list.size() - 1), bt.getAddress()); // puts position => address
editor.commit();
}
} else {
Toast.makeText(context, "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
address = listIndexToDeviceAddress.getString(String.valueOf(position), "address not available");
if (address.equals("address not available")){
Toast.makeText(context, "Something went wrong, address not found", Toast.LENGTH_LONG).show();
}else {
new ConnectBT().execute(); //Call the class to connect
}
}
}); //Method called when the device from the list is clicked
//handling long click
devicelist.setOnItemLongClickListener (new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent,final View view, final int position, long id) {
// TODO Auto-generated method stub
android.support.v7.app.AlertDialog.Builder builderSingle = new android.support.v7.app.AlertDialog.Builder(context);
// can be used for icon and label:
//builderSingle.setIcon(R.drawable.ic_logo);
// builderSingle.setTitle("Select One Name:-");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.select_dialog_singlechoice);
// hardcoded options
arrayAdapter.add("Enter New Name");
arrayAdapter.add("Set Password");
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
if (which == 0){ // delete
//do your stuff here
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.name_prompt, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
Log.d("length", String.valueOf(userInput.getText().toString().length()));
if (userInput.getText().toString().length() > 0) {
SharedPreferences.Editor editor = deviceListSharedPreferences.edit();
String device_address = listIndexToDeviceAddress.getString(String.valueOf(position), "address not available");
if (!device_address.equals("address not available")) {
editor.putString(device_address, userInput.getText().toString());
editor.commit();
pairedDevicesList();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Name empty", Toast.LENGTH_SHORT).show();
}
}
})
.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();
}else if (which == 1){ // share
//do your stuff here
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.name_prompt, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final TextView tv = (TextView) promptsView.findViewById(R.id.name_prompt_label);
tv.setText("Enter New Password");
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// set password
Log.d("length", String.valueOf(userInput.getText().toString().length()));
if (userInput.getText().toString().length() > 0) {
// are you sure this is the new password?
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
// update or create new password
String device_address = listIndexToDeviceAddress.getString(String.valueOf(position), "address not available");
String device_name = deviceListSharedPreferences.getString(device_address, ((String)devicelist.getItemAtPosition(position)).split("\n")[0]); //get saved name otherwise get first line from ListView string
if (!device_address.equals("address not available")) {
Log.v("address and name", device_address);
mdb.updateOrSetNewPassword(device_name, device_address, userInput.getText().toString(), true);
Toast.makeText(context, "New Password Set", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
dialog.dismiss();
break;
}
}
};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to change the password to " + userInput.getText().toString() + "?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
} else {
Toast.makeText(context, "Password field empty empty", Toast.LENGTH_SHORT).show();
}
}
})
.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();
}
}
});
builderSingle.show();
return true;
}
});
}
}
Here is my Logcat:
logcat1
logcat2
Here is my database structure:

You forgot to initialize your mAuth
mAuth = FirebaseAuth.getInstance();
This will make emaill null

I suspect emaill is empty or null in this statement:
mdShare.child(emaill).addValueEventListener(new ValueEventListener() {...}
Look at your log output to see what is logged for these statements:
System.out.println("Email add:" + emaill);
...
System.out.println(emaill+"HEH");
Also look at the output from these statements. Perhaps there is no signed-in user, so getCurrentUser() is returning null. It is also possible that there is a user, but there is no email address in his/her profile. And as #Indra correctly points out, you haven't initialized mAuth.
try {
emaill = mAuth.getCurrentUser().getEmail();
emaill = emaill.replace(".", "<");
System.out.println("Email add:" + emaill);
}catch(NullPointerException n){
System.out.println(n.getMessage());
}

Related

How can I make Alert dialog box to work correctly in Async after executing doInBackground method

public void book(View c)
{
DoLogin doLogin = new DoLogin();
doLogin.execute("");
finish();
}
public class DoLogin extends AsyncTask<String, String, String> {
String Docdate = docdate.getText().toString().trim();
String Docpre = docprefix.getText().toString().trim();
String Cname = cname.getSelectedItem().toString().trim();
String Product = pname.getSelectedItem().toString().trim();
String Dest = dest.getSelectedItem().toString().trim();
String Dname = dname.getSelectedItem().toString().trim();
String Qty = qty.getText().toString().trim();
String Remarks = remarks.getText().toString().trim();
String Duedt = duedt.getText().toString().trim();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(OrderEntry.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
final AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(mContext);
alertDialogBuilder.setMessage("Would You like to Confirm
Your Order?");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int
arg1) {
try {
rs1 = stmt.executeQuery(Qr);
if (rs1.next()) {
Toast.makeText(mContext,
"hiiiiiiiiiiiiii", Toast.LENGTH_SHORT).show();
Intent i = new
Intent(OrderEntry.this, OrderRequest.class);
startActivity(i);
} else {
Toast.makeText(mContext,
"byeeeeeeeeeeeee", Toast.LENGTH_SHORT).show();
}
} catch (Exception v) {
Log.e("insert", v + "");
}
}
});
alertDialogBuilder.setNegativeButton("No", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
isSuccess1 = false;
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
protected String doInBackground(String... params) {
try {
Connection conn = (Connection) connectionClass.CONN();
if (conn == null) {
z = "Error in connection with SQL server";
} else {
Qr = "insert into [Dealer].[dbo].[BookingOrder]
(DocDate,DocPrefix,CustomerName,Destination,
DealerName,Productname,Quantity,Remarks,DueDate)
values('" + Docdate + "','" + Docpre + "','" + Cname + "',
'" + Dest + "','" + Dname + "','" + Product + "','"
+ Qty + "','" + Remarks + "','" + Duedt + "')";
stmt = conn.createStatement();
z = "confirmation";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
Log.e("con", ex + "");
}
}
return z;
}
}
> LOGCAT ERRORS:
/WindowManager: android.view.WindowLeaked: Activity
com.example.admin.dealerdemo.OrderEntry has leaked window
com.android.internal.policy.PhoneWindow$DecorView{dba0674
V.E...... R.....I. 0,0-639,188} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:368)
at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at
com.example.admin.dealerdemo.OrderEntry$DoLogin$override.
onPostExecute(OrderEntry.java:295)
at
com.example.admin.dealerdemo.OrderEntry$DoLogin$override.
access$dispatch(OrderEntry.java)
at com.example.admin.dealerdemo.OrderEntry$DoLogin.
onPostExecute(OrderEntry.java:0)
at com.example.admin.dealerdemo.OrderEntry$DoLogin
.onPostExecute(OrderEntry.java:231)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at
android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
run(ZygoteInit.java:726)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I have to Confirm the order before clicking on (book :Method)Book your Order button.I am getting above exception.How can I handle this exception ?Please help me to overcome this problem.Thanks in Advance.
Cancel the current alertDialog before start another Activity. call alertDialog.dismiss()
#Override
protected void onPostExecute(String r) {
Toast.makeText(OrderEntry.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
final AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(mContext);
alertDialogBuilder.setMessage("Would You like to Confirm
Your Order?");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int
arg1) {
try {
alertDialog.dismiss();
rs1 = stmt.executeQuery(Qr);
if (rs1.next()) {
Toast.makeText(mContext,
"hiiiiiiiiiiiiii", Toast.LENGTH_SHORT).show();
Intent i = new
Intent(OrderEntry.this, OrderRequest.class);
startActivity(i);
} else {
alertDialog.dismiss();
Toast.makeText(mContext,
"byeeeeeeeeeeeee", Toast.LENGTH_SHORT).show();
}
} catch (Exception v) {
Log.e("insert", v + "");
}
}
});
alertDialogBuilder.setNegativeButton("No", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
isSuccess1 = false;
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
You need to post the code from your doInBackground method as well. It is possible that your activity is somehow exited during that method, so trying to create an AlertDialog from "mContext" (whatever that is, show the rest of your code) causes a window leak.
This other question may have what you need: Activity has leaked window that was originally added
The problem is likely that you need to dismiss() your AlertDialog before changing/leaving activities, or you need to make sure the activity is active before you create it.

android connected with ftp

I have download the below code from this website
I can successfully login in filezilla client. But when i typed the same information in this app, it shows (unable to perform action). can anyone help me?
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
private static final String TEMP_FILENAME = "TAGtest.txt";
private Context cntx = null;
private MyFTPClientFunctions ftpclient = null;
private Button btnLoginFtp, btnUploadFile, btnDisconnect, btnExit;
private EditText edtHostName, edtUserName, edtPassword;
private ProgressDialog pd;
private String[] fileList;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (msg.what == 0) {
getFTPFileList();
} else if (msg.what == 1) {
showCustomDialog(fileList);
} else if (msg.what == 2) {
Toast.makeText(MainActivity.this, "Uploaded Successfully!",
Toast.LENGTH_LONG).show();
} else if (msg.what == 3) {
Toast.makeText(MainActivity.this, "Disconnected Successfully!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Unable to Perform Action!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cntx = this.getBaseContext();
edtHostName = (EditText) findViewById(R.id.edtHostName);
edtUserName = (EditText) findViewById(R.id.edtUserName);
edtPassword = (EditText) findViewById(R.id.edtPassword);
btnLoginFtp = (Button) findViewById(R.id.btnLoginFtp);
btnUploadFile = (Button) findViewById(R.id.btnUploadFile);
btnDisconnect = (Button) findViewById(R.id.btnDisconnectFtp);
btnExit = (Button) findViewById(R.id.btnExit);
btnLoginFtp.setOnClickListener(this);
btnUploadFile.setOnClickListener(this);
btnDisconnect.setOnClickListener(this);
btnExit.setOnClickListener(this);
// Create a temporary file. You can use this to upload
createDummyFile();
ftpclient = new MyFTPClientFunctions();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLoginFtp:
if (isOnline(MainActivity.this)) {
connectToFTPAddress();
} else {
Toast.makeText(MainActivity.this,
"Please check your internet connection!",
Toast.LENGTH_LONG).show();
}
break;
case R.id.btnUploadFile:
pd = ProgressDialog.show(MainActivity.this, "", "Uploading...",
true, false);
new Thread(new Runnable() {
public void run() {
boolean status = false;
status = ftpclient.ftpUpload(
Environment.getExternalStorageDirectory()
+ "/TAGFtp/" + TEMP_FILENAME,
TEMP_FILENAME, "/", cntx);
if (status == true) {
Log.d(TAG, "Upload success");
handler.sendEmptyMessage(2);
} else {
Log.d(TAG, "Upload failed");
handler.sendEmptyMessage(-1);
}
}
}).start();
break;
case R.id.btnDisconnectFtp:
pd = ProgressDialog.show(MainActivity.this, "", "Disconnecting...",
true, false);
new Thread(new Runnable() {
public void run() {
ftpclient.ftpDisconnect();
handler.sendEmptyMessage(3);
}
}).start();
break;
case R.id.btnExit:
this.finish();
break;
}
}
private void connectToFTPAddress() {
final String host = edtHostName.getText().toString().trim();
final String username = edtUserName.getText().toString().trim();
final String password = edtPassword.getText().toString().trim();
if (host.length() < 1) {
Toast.makeText(MainActivity.this, "Please Enter Host Address!",
Toast.LENGTH_LONG).show();
} else if (username.length() < 1) {
Toast.makeText(MainActivity.this, "Please Enter User Name!",
Toast.LENGTH_LONG).show();
} else if (password.length() < 1) {
Toast.makeText(MainActivity.this, "Please Enter Password!",
Toast.LENGTH_LONG).show();
} else {
pd = ProgressDialog.show(MainActivity.this, "", "Connecting...",
true, false);
new Thread(new Runnable() {
public void run() {
boolean status = false;
status = ftpclient.ftpConnect(host, username, password, 21);
if (status == true) {
Log.d(TAG, "Connection Success");
handler.sendEmptyMessage(0);
} else {
Log.d(TAG, "Connection failed");
handler.sendEmptyMessage(-1);
}
}
}).start();
}
}
private void getFTPFileList() {
pd = ProgressDialog.show(MainActivity.this, "", "Getting Files...",
true, false);
new Thread(new Runnable() {
#Override
public void run() {
fileList = ftpclient.ftpPrintFilesList("/");
handler.sendEmptyMessage(1);
}
}).start();
}
public void createDummyFile() {
try {
File root = new File(Environment.getExternalStorageDirectory(),
"TAGFtp");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, TEMP_FILENAME);
FileWriter writer = new FileWriter(gpxfile);
writer.append("Hi this is a sample file to upload for android FTP client example from TheAppGuruz!");
writer.flush();
writer.close();
Toast.makeText(this, "Saved : " + gpxfile.getAbsolutePath(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
private void showCustomDialog(String[] fileList) {
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom);
dialog.setTitle("/ Directory File List");
TextView tvHeading = (TextView) dialog.findViewById(R.id.tvListHeading);
tvHeading.setText(":: File List ::");
if (fileList != null && fileList.length > 0) {
ListView listView = (ListView) dialog
.findViewById(R.id.lstItemList);
ArrayAdapter<String> fileListAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, fileList);
listView.setAdapter(fileListAdapter);
} else {
tvHeading.setText(":: No Files ::");
}
Button dialogButton = (Button) dialog.findViewById(R.id.btnOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}

Android contact picker returning nulll (resultCode == 0)

I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.

android textview does not show after setting visible from another thread

I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
e.printStackTrace();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
thread.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);

Android cannot bind to service (In App-Billing)

I'm trying to implement in app-billing in my application, but I have a little problem with it. I'm using the example from android developer's site and everytime I start the activity which will connect to the billing service it's showing me a dialog that I cannot connect to server and when I press learn more it's going to a web page which is explaining me to update my android market app, but it's already the latest one. And the other thing, before implementing the code on my application I create a test application where I can connect with the same code and I don't get problems. But in my application I can't do that. Is there any connection with the developer api key, which you can use only in one application or something like that. Because I'm using the same for test and real app.
And here is my code if you can see something which is not really like it should be :
public class StampiiStore extends Activity {
String servername;
int userId;
int storageID;
RPCCommunicator rpc;
String path;
Button envelope1, envelope2, envelope3;
private static final String TAG = "STAMPII";
/**
* The SharedPreferences key for recording whether we initialized the
* database. If false, then we perform a RestoreTransactions request
* to get all the purchases for this user.
*/
private static final String DB_INITIALIZED = "db_initialized";
private mStampiiPurchaseObserver mStampiiPurchaseObserver;
private Handler mHandler;
private BillingService mBillingService;
private TextView mLogTextView;
private Cursor mOwnedItemsCursor;
private PurchaseDatabase mPurchaseDatabase;
private Set<String> mOwnedItems = new HashSet<String>();
/**
* The developer payload that is sent with subsequent
* purchase requests.
*/
private static final int DIALOG_CANNOT_CONNECT_ID = 1;
private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2;
#SuppressWarnings("static-access")
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.store);
SystemDatabaseHelper sysDbHelper = new SystemDatabaseHelper(this, null, 1);
sysDbHelper.initialize(this);
ImageView icon = (ImageView) findViewById (R.id.store_img);
final int collId = getIntent().getIntExtra("collection_id",0);
Log.e("collId","collId : "+collId);
// Getting all variables from SharedPreferences to build the right path to images
servername = rpc.getCurrentServerName(this);
Log.d("","Current Server Name : "+servername);
userId = rpc.getUserId(this);
Log.d("","User Id : "+userId);
storageID = rpc.getCurrentStoragePath(this);
Log.d("","storage ID : "+storageID);
//
TextView colltitle = (TextView) findViewById(R.id.collection_title);
TextView sTitle = (TextView) findViewById(R.id.store_collId);
TextView collInfo = (TextView) findViewById(R.id.store_coll_info);
envelope1 = (Button) findViewById(R.id.buyone);
envelope1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingService.requestPurchase("android.test.purchased", "");
}
});
envelope2 = (Button) findViewById(R.id.buytwo);
envelope2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingService.requestPurchase("android.test.canceled", "");
}
});
envelope3 = (Button) findViewById(R.id.buythree);
envelope3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingService.requestPurchase("com.stampii.stampii.envelopesthree", "");
}
});
mHandler = new Handler();
mStampiiPurchaseObserver = new mStampiiPurchaseObserver(mHandler);
mBillingService = new BillingService();
mBillingService.setContext(this);
mPurchaseDatabase = new PurchaseDatabase(this);
setupWidgets();
// Check if billing is supported.
ResponseHandler.register(mStampiiPurchaseObserver);
if (!mBillingService.checkBillingSupported()) {
showDialog(DIALOG_CANNOT_CONNECT_ID);
}
Button back = (Button) findViewById(R.id.store_back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = settings.getBoolean("isLoggedIn", false);
ImageButton sync = (ImageButton) findViewById(R.id.sync_store);
if(isLoggedIn){
sync.setVisibility(View.VISIBLE);
} else if(!isLoggedIn){
sync.setVisibility(View.GONE);
}
sync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(StampiiStore.this, Synchronization.class);
intent.putExtra("process", 2);
startActivity(intent);
}
});
String titleSql = "SELECT title FROM collection_lang WHERE collection_id= " + collId + " AND lang_code='en_US'";
Cursor title = sysDbHelper.executeSQLQuery(titleSql);
if(title.getCount()==0){
title.close();
} else if(title.getCount()>0){
for(title.move(0); title.moveToNext(); title.isAfterLast()){
String collectionTitle = title.getString(title.getColumnIndex("title"));
sTitle.setText(collectionTitle);
if (collectionTitle.length() > 20){
String newTitle = collectionTitle.substring(0, 20);
colltitle.setText(newTitle + "...");
} else {
colltitle.setText(collectionTitle);
}
}
}
title.close();
String infoSql = "SELECT DISTINCT c.total_cards AS cardsCount, " +
" c.cards_per_envelope AS cardsPerEnvelope " +
"FROM collections AS c, collection_lang AS cl " +
"WHERE c.collection_id = cl.collection_id AND c.collection_id=" + collId;
Cursor info = sysDbHelper.executeSQLQuery(infoSql);
if(info.getCount()==0){
info.close();
} else if (info.getCount()>0){
info.moveToFirst();
int cardsCount = info.getInt(info.getColumnIndex("cardsCount"));
int cardsPerEnvelope = info.getInt(info.getColumnIndex("cardsPerEnvelope"));
collInfo.setText(cardsCount+" Stampii\n"+cardsPerEnvelope+" cards per envelope");
}
String sqlite2 = "SELECT media_id FROM collection_media WHERE collection_id="+collId+" AND media_type_id="+3018;
Cursor bg = sysDbHelper.executeSQLQuery(sqlite2);
if (bg.getCount() == 0) {
bg.close();
} else if (bg.getCount() > 0) {
for (bg.move(0); bg.moveToNext(); bg.isAfterLast()) {
int objectId = Integer.parseInt(bg.getString(bg.getColumnIndex("media_id")));
String filename = "mediacollection-"+objectId+".png";
//if(storageID==1){
path = rpc.getPublicPathsInternal(servername, 3018, filename, StampiiStore.this);
/*} else if(storageID==2){
path = rpc.getPublicPathsExternal(servername, 3007, objectId);
}*/
}
}
bg.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[3*1024];
Bitmap ops = BitmapFactory.decodeFile(path, options);
BitmapDrawable bitmapDrawable = new BitmapDrawable(ops);
icon.setBackgroundDrawable(bitmapDrawable);
Button promoCode = (Button) findViewById(R.id.promo_code_btn);
promoCode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences isSelectedCode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String isSelected = isSelectedCode.getString("isSelected", "");
Log.i("isSelected", "isSelected" + isSelected);
EditText input = new EditText(StampiiStore.this);
input.setText(isSelected);
final int loggedOut = getIntent().getIntExtra("statement", 0);
if(loggedOut==0){
new AlertDialog.Builder(getParent())
.setTitle("Promotional Code")
.setView(input)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Positive");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog","Negative");
dialog.cancel();
}
}).show();
} else if (loggedOut==1){
new AlertDialog.Builder(Collections.parentActivity)
.setTitle("Promotional Code")
.setView(input)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Positive");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog","Negative");
dialog.cancel();
}
}).show();
}
}
});
Button savedCodes = (Button) findViewById(R.id.saved_codes_btn);
savedCodes.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent previewMessage = new Intent(getParent(), SavedCodes.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("Saved Codes", previewMessage);
}
});
}
/**
* Sets up the UI.
*/
private void setupWidgets() {
//TODO: If need any changes in the UI!
}
/**
* If the database has not been initialized, we send a
* RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items
* for this user. This happens if the application has just been installed
* or the user wiped data. We do not want to do this on every startup, rather, we want to do
* only when the database needs to be initialized.
*/
private void restoreDatabase() {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
boolean initialized = prefs.getBoolean(DB_INITIALIZED, false);
if (!initialized) {
mBillingService.restoreTransactions();
Toast.makeText(this, "Restoring Transactions", Toast.LENGTH_LONG).show();
}
}
private void prependLogEntry(CharSequence cs) {
SpannableStringBuilder contents = new SpannableStringBuilder(cs);
contents.append('\n');
contents.append(mLogTextView.getText());
mLogTextView.setText(contents);
}
private void logProductActivity(String product, String activity) {
SpannableStringBuilder contents = new SpannableStringBuilder();
contents.append(Html.fromHtml("<b>" + product + "</b>: "));
contents.append(activity);
prependLogEntry(contents);
}
//PurchaseObserver
private class mStampiiPurchaseObserver extends PurchaseObserver {
public mStampiiPurchaseObserver(Handler handler) {
super(StampiiStore.this, handler);
}
#Override
public void onBillingSupported(boolean supported) {
if (Consts.DEBUG) {
Log.i(TAG, "supported: " + supported);
}
if (supported) {
restoreDatabase();
envelope1.setEnabled(true);
envelope2.setEnabled(true);
envelope3.setEnabled(true);
} else {
showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
}
}
#Override
public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
int quantity, long purchaseTime, String developerPayload) {
if (Consts.DEBUG) {
Log.i(TAG, "onPurchaseStateChange() itemId: " + itemId + " " + purchaseState);
}
if (developerPayload == null) {
logProductActivity(itemId, purchaseState.toString());
} else {
logProductActivity(itemId, purchaseState + "\n\t" + developerPayload);
}
if (purchaseState == PurchaseState.PURCHASED) {
mOwnedItems.add(itemId);
}
mOwnedItemsCursor.requery();
}
#Override
public void onRequestPurchaseResponse(RequestPurchase request,
ResponseCode responseCode) {
if (Consts.DEBUG) {
Log.d(TAG, request.mProductId + ": " + responseCode);
}
if (responseCode == ResponseCode.RESULT_OK) {
if (Consts.DEBUG) {
Log.i(TAG, "purchase was successfully sent to server");
}
logProductActivity(request.mProductId, "sending purchase request");
} else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
if (Consts.DEBUG) {
Log.i(TAG, "user canceled purchase");
}
logProductActivity(request.mProductId, "dismissed purchase dialog");
} else {
if (Consts.DEBUG) {
Log.i(TAG, "purchase failed");
}
logProductActivity(request.mProductId, "request purchase returned " + responseCode);
}
}
#Override
public void onRestoreTransactionsResponse(RestoreTransactions request,
ResponseCode responseCode) {
if (responseCode == ResponseCode.RESULT_OK) {
if (Consts.DEBUG) {
Log.d(TAG, "completed RestoreTransactions request");
}
// Update the shared preferences so that we don't perform
// a RestoreTransactions again.
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(DB_INITIALIZED, true);
edit.commit();
} else {
if (Consts.DEBUG) {
Log.d(TAG, "RestoreTransactions error: " + responseCode);
}
}
}
}
/**
* Called when this activity becomes visible.
*/
#Override
protected void onStart() {
super.onStart();
ResponseHandler.register(mStampiiPurchaseObserver);
}
/**
* Called when this activity is no longer visible.
*/
#Override
protected void onStop() {
super.onStop();
ResponseHandler.unregister(mStampiiPurchaseObserver);
}
#Override
protected void onDestroy() {
super.onDestroy();
mPurchaseDatabase.close();
mBillingService.unbind();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CANNOT_CONNECT_ID:
return createDialog("Server cannot Connect",
"Server cannot connect");
case DIALOG_BILLING_NOT_SUPPORTED_ID:
return createDialog("Billing not supported",
"Billing not supported");
default:
return null;
}
}
/**
* Replaces the language and/or country of the device into the given string.
* The pattern "%lang%" will be replaced by the device's language code and
* the pattern "%region%" will be replaced with the device's country code.
*
* #param str the string to replace the language/country within
* #return a string containing the local language and region codes
*/
private String replaceLanguageAndRegion(String str) {
// Substitute language and or region if present in string
if (str.contains("%lang%") || str.contains("%region%")) {
Locale locale = Locale.getDefault();
str = str.replace("%lang%", locale.getLanguage().toLowerCase());
str = str.replace("%region%", locale.getCountry().toLowerCase());
}
return str;
}
private Dialog createDialog(String titleId, String messageId) {
String helpUrl = replaceLanguageAndRegion(getString(R.string.help_url));
if (Consts.DEBUG) {
Log.i(TAG, helpUrl);
}
final Uri helpUri = Uri.parse(helpUrl);
AlertDialog.Builder builder = null;
final int loggedOut = getIntent().getIntExtra("statement", 0);
if(loggedOut==0){
builder = new AlertDialog.Builder(getParent());
builder.setTitle(titleId)
.setIcon(android.R.drawable.stat_sys_warning)
.setMessage(messageId)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton("Learn More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, helpUri);
startActivity(intent);
}
});
} else if(loggedOut==1){
builder = new AlertDialog.Builder(Collections.parentActivity);
builder.setTitle(titleId)
.setIcon(android.R.drawable.stat_sys_warning)
.setMessage(messageId)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton("Learn More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, helpUri);
startActivity(intent);
}
});
}
return builder.create();
}
#Override
public void onRestart(){
super.onRestart();
Intent previewMessage = new Intent(StampiiStore.this, StampiiStore.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("StampiiStore", previewMessage);
this.finish();
}
}
And here is how I'm declaring the service in manifest file :
<service android:name="BillingService" />
<receiver android:name="BillingReceiver">
<intent-filter>
<action android:name="com.android.vending.billing.IN_APP_NOTIFY" />
<action android:name="com.android.vending.billing.RESPONSE_CODE" />
<action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" />
</intent-filter>
</receiver>
Any suggestions how to connect to the market?
I had the same issue and probably your mistake is the same as mine. I was using a TabHost in my activities and I find out that TabSpec cannot bind to services. So check this :
Using getApplicationContext().bindService instead of just bindService
on your activity solves the problem as it is using the higher level
application context.
Can't you debug through that code? Probably, mBillingService.checkBillingSupported() returns false, caused by failing BillingService.bindToMarketBillingService().
i was facing problem like that on my sony ericssion w8 2.1 android device
what i did are the following :
1) getApplicationContext().bindService (as android-droid said)
2) reset my mobile and downloaded apk for market 2.3.4 version and installed it
3) then open the market app on mobile and clicked accepted and when the app i quitted
4) rerunned the app it was working fine
note: before doing this i tested my app on other device using market version 3.x and it was working so i did all these things ...

Categories

Resources