How do I access my UI from MainActivity from Broadcast Receiver class - java

I am new to Android Studio and I am creating a custom notification app, and I wanted to use the EditText from my MainActivity class in Broadcast Receiver class. How can I do that?
Broadcast Receiver code:
`package com.example.notificationscreator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.EditText;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder Build = new NotificationCompat.Builder(context, "Notified");
Build.setSmallIcon(R.drawable.ic_stat_name);
Build.setContentTitle("");
Build.setStyle(new NotificationCompat.BigTextStyle().bigText(""));
NotificationManagerCompat Managercompats = NotificationManagerCompat.from(context);
Managercompats.notify(1, Build.build());
}
}`
Main activity code:
`package com.example.notificationscreator;
import static com.example.notificationscreator.R.*;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Calendar;
import java.util.Random;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main2);
Button btnmain = findViewById(R.id.button4);
Button Displaynotif = findViewById(R.id.button3);
EditText Timedisplay = findViewById(R.id.editTextTime);
Integer Time = Integer.parseInt(Timedisplay.getText().toString());
btnmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Backmainpage();
}
});
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("Notified","Notification", NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
Displaynotif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int Randnum = new Random().nextInt(80);
Intent intent= new Intent(MainActivity2.this,MyReceiver.class);
PendingIntent pendingintention = PendingIntent.getBroadcast(MainActivity2.this,0, intent,0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
long timeonclick = System.currentTimeMillis();
long timeafterclick = 10000;
am.set(AlarmManager.RTC_WAKEUP,timeonclick+timeafterclick,pendingintention);
}
});
}
public void Backmainpage(){
Intent intention2 = new Intent(this,MainActivity.class);
startActivity(intention2);
}
}`
I've tried recalling Main Activity using
MainActivity2 Mainactivity = new MainActivity2();
but I still can't access the UI from Main Activity

You can use another BroadcastReceiver to communicate with your activity like below example.
add the following code inside your broadcast receiver.
#Override
public void onReceive(Context context, Intent intent) {
//... your other code
Intent intent = new Intent();
intent.setAction("CustomAction"); // use your action name
intent.putExtra("key", "Value"); // you can pass data like this
context.sendBroadcast(intent); // fire broadcast receiver
}
Now, register your custom broadcast receiver from Activity
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("CustomAction"); // use your custom action name
BroadcastReceiver updateUIReciver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//You will get your data here
//Update UI based on your data.
if (intent != null) {
String data = intent.getStringExtra("key");
}
}
};
registerReceiver(updateUIReciver, filter); // register broad cast receiver.
}

public class MainActivity2 extends AppCompatActivity {
EditText Timedisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main2);
Timedisplay = findViewById(R.id.editTextTime);
//register your broadcast here
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("messageevent"));
}
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("key");
Log.e(TAG, "Got message: " + message);
if(message != null && !message.isEmpty()) {
//Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
String timedisplay = Timedisplay.getText();
}
}
};
//call this from anywhere you want to trigger the broadcoast
Intent i = new Intent("messageevent");
// You can also include some extra data.
i.putExtra("key", "value");
LocalBroadcastManager.getInstance(CheckUpdate.this).sendBroadcast(i);

Related

discussing getActivityResult in class

There must be a way to get intent result in a class without using onActivityResult. By using other methods...
I dont know how, but Iam sure there is a way.
My class that should get the result of the intent filepicker from this class without using onActivityResult in the MainActivity.java that extents activity. FilePicker.java
package com.hadiawali.codeeditor;
import android.content.Intent;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
public class FilePicker {
Intent filePicker = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
public static void startPicking(Activity activity) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Intent chooseFolder = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
chooseFolder.addCategory(Intent.CATEGORY_DEFAULT);
activity.startActivityForResult(Intent.createChooser(chooseFolder, "Choose directory"), 9999);
}
}
}
My class that extents activity. MainActivity.java
package com.hadiawali.codeeditor;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
FilePicker.startPicking(MainActivity.this);
//I need to get the intent reslut from the class without using onActivityResult
}
});
}
}
For example you send to intent from activity A to B then
in Activity A create Activity Result like below
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// callback called
}
}
});
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//call B activity
someActivityResultLauncher.launch(intent);
}
in Activity B your task is successfully complete then set
setResult(RESULT_OK);
finish();
or if task is not complete successfully then put
setResult(RESULT_CANCELED);
finish();

How to sound notifications sound when new Message arrives from Firebase Realtime Data base

I'm using below code in my chat applicaiton where it uses RealTime Firebase Data base to chat among users.
I would like to use an notification sound when new message arrives and also have an option on toolbar to turn it off or on.
Is it possible.
Here is the code of Chat_Room
package com.nepalpolice.mnemonics.chat;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.nepalpolice.mnemonics.R;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by filipp on 6/28/2016.
*/
public class Chat_Room extends AppCompatActivity{
private Button btn_send_msg;
private EditText input_msg;
private TextView chat_conversation;
private Toolbar mainToolbar;
private String user_name,room_name;
private DatabaseReference root ;
private String temp_key;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
btn_send_msg = (Button) findViewById(R.id.btn_send);
input_msg = (EditText) findViewById(R.id.msg_input);
chat_conversation = (TextView) findViewById(R.id.textView);
user_name = getIntent().getExtras().get("user_name").toString();
room_name = getIntent().getExtras().get("room_name").toString();
mainToolbar = (Toolbar) findViewById(R.id.main_chat);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle(" Room - "+room_name);
root = FirebaseDatabase.getInstance().getReference().child(room_name);
btn_send_msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
root.updateChildren(map);
DatabaseReference message_root = root.child(temp_key);
Map<String,Object> map2 = new HashMap<String, Object>();
map2.put("name",user_name);
map2.put("msg",input_msg.getText().toString());
message_root.updateChildren(map2);
input_msg.getText().clear();
}
});
root.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private String chat_msg,chat_user_name;
private void append_chat_conversation(DataSnapshot dataSnapshot) {
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
chat_msg = (String) ((DataSnapshot)i.next()).getValue();
chat_user_name = (String) ((DataSnapshot)i.next()).getValue();
chat_conversation.append(chat_user_name +" : "+chat_msg +" \n");
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
and my Firebase Data Structure is
Firebase Data Structure Image
Thanks in advance.
my Mainactivity file is
package com.nepalpolice.mnemonics.chat;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nepalpolice.mnemonics.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
private Toolbar mainToolbar;
private Button add_room;
private EditText room_name;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String username = "userKey";
SharedPreferences sharedpreferences;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_rooms = new ArrayList<>();
private String name;
private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mainToolbar = (Toolbar) findViewById(R.id.main_chatbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle("Chat Rooms");
progressBar= (ProgressBar) findViewById(R.id.webViewProgressfaq);
add_room = (Button) findViewById(R.id.btn_add_room);
room_name = (EditText) findViewById(R.id.room_name_edittext);
listView = (ListView) findViewById(R.id.listView);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list_of_rooms);
listView.setAdapter(arrayAdapter);
add_room.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<String, Object>();
map.put(room_name.getText().toString(),"");
root.updateChildren(map);
}
});
if(isNetworkStatusAvialable (getApplicationContext())) {
request_user_name();
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
list_of_rooms.clear();
list_of_rooms.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
Toast.makeText(getBaseContext(), "You're Offline!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.VISIBLE);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),Chat_Room.class);
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
startActivity(intent);
}
});
}
private void request_user_name() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
final String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
else
{
dialogInterface.cancel();
request_user_name();
}
}
});
builder.show();
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
You should add FirebaseMessaging for notifications. And set sound when notification recieve. refer this link. It will help. Also learn how to use firebase functions. Firebase functions will help you to triger the realtime database from cloud to android. Firebase functions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder = new NotificationCompat.Builder(this, "")
.setColor(context.getResources().getColor(R.color.colorGreen))
.setContentText(body)
.setSmallIcon(R.drawable.white_logo)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image).setSummaryText(body))
.setContentTitle(title + "\n")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(defaultSoundUri);
} else {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder = new NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.white_logo)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image).setSummaryText(body))/*Notification with Image*/
.setContentTitle(title + "\n")
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri);
}
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
You could use a radioButton,listen to its state then save it to SharedPreference. Heres how
SharedPreferences.Editor editor = getSharedPreferences("MyApp", MODE_PRIVATE).edit();
editor.putBoolean("allowNotification", radioButton.isChecked());
editor.apply();
and to read preference
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
boolean allowNOtific = prefs.getBoolean("allowNotification", false);
radioButton.setChecked(allowNOtific);
and to create and sound notification, and allow it as clickable link to your activity
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(subject)
.setContentText(object.getString("body"))
.setAutoCancel(true)
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, ToneGenerator.MAX_VOLUME);
toneG.startTone(ToneGenerator.TONE_CDMA_HIGH_L, 3000);
((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(2000);
Note: Vibrate need this permission
<uses-permission android:name="android.permission.VIBRATE" />
Hope this helps
Edit:
The error is in Chat_Room so basically it is considered different question. My suspect is that your .hasNext() still returns true which causes the error. I havent tried such approach so im not sure. How about you try my approach, heres a sample code
for (DataSnapshot messageThread : dataSnapshot.getChildren()) {
String lastMessage = (String) messageThread.child("lastMessage").getValue();
}

Android app fails to connect with MySQL database

I have a .sql database which I edit using PHPmyadmin and a android app that retrieves the login credentials from the database and tries to login to the app according to the user's credentials. But it keeps showing "Unable to login" error in the app even though I use the correct credentials from the database, which in this case is phoneno and password. The Login_Activity.JAVA is as below. Why is the app not logging in properly?
Login_Activity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}

Error: View cannot be applied to Intent

I'm new to Android App Development and creating a simple service app. It has a button to start service and a button to stop service with their repective methods. Following is my code:
App3_main.java
package eg.app3;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class App3_main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app3_main);
}
public void startservice(View view)
{
Intent intent = new Intent(this,MyService.class);
startservice(intent); //this is where I'm getting the error mentioned in the title
}
public void stopservice(View view)
{
Intent intent = new Intent(this,MyService.class);
stopservice(intent); //this is where I'm getting the error mentioned in the title
}
}
MyService.java
package eg.app3;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped",Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Please guide me where I'm wrong.
Replace:
startservice(intent);
with:
startService(intent);
Then, replace:
stopservice(intent);
with:
stopService(intent);
Like most programming languages, Java is case-sensitive.

Testing android in app billing doesn't show any products when bebugging

I have a simple app that has an unlock feature in it. When a user purchases this they can unlock more content in the app.
When I debug the app I don't get any errors, but I am unable to retrieve a list of products using the google billing services.
On my main activity I would like to check if the user has all ready purchased the "upgrade" if they have do something with that information.
I have been following the api documentation but its not really helping.
In App Billing Reference
Implementation
Testing
I have 1 item in my In-app products, I have followed the testing document and added an apk to my Alpha testing. The problem here is that apk cant have debugging enabled, so when I use the debugger in android studio the app may perform differently??
I think my code is OK,but any help or guidance in how to test this would be great.
MainActivity.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
IInAppBillingService mService;
ServiceConnection connection;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button start = (Button) findViewById(R.id.startgame);
Button settings = (Button) findViewById(R.id.about);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StartGame.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Settings.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
/// check for pro unlock
serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
// first this
connection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("BILLING", "Connected");
//purchse info
mService = IInAppBillingService.Stub.asInterface(service);
checkPurchaseInfo();
}
};
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
}
private void checkPurchaseInfo() {
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
int responseCode = ownedItems.getInt("RESPONSE_CODE");
Log.d("BILLING","Request Code: " + responseCode);
if(responseCode == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.d("OWNED",ownedSkus.toString());
Log.d("purcahseList",purchaseDataList.toString());
Log.d("SIGNLIST",signatureList.toString());
/////////
//all of these arrays come back as empty []
////////
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);
}
}
}

Categories