Making a call when button pressed on Arduino - android

Hi I'm trying to combine 2 projects
1. that tells me wen button on arduino pressed
2. make a call on android
what im trying to do is when button pressed on arduino make a call..
but with no luck :(
Call
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class phonecalls extends Activity {
private void call() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:048598077"));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
}
}
buttons
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import net.mitchtech.adb.phonecalls;
import org.microbridge.server.AbstractServerListener;
import org.microbridge.server.Server;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class ButtonView extends FrameLayout {
private static final String TAG = ButtonView.class.getSimpleName();
private final View mButtonView;
private Server mServer;
private final int BUTTON1 = 2;
private final int BUTTON2 = 3;
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mButtonView = inflater.inflate(R.layout.input, this);
}
public void setServer(Server server) {
mServer = server;
mServer.addListener(new AbstractServerListener() {
#Override
public void onReceive(org.microbridge.server.Client client, byte[] data) {
if (data.length < 2)
return;
final int pinNumber = data[0];
final int pinState = data[1];
Log.i(TAG, "data[0]:" + pinNumber + " data[1]:" + pinState);
final TextView positionText = (TextView) findViewById(R.id.activeText);
class InputAction implements Runnable {
public void run() {
switch (pinNumber) {
case BUTTON1:
if (pinState == 1) {
call();
positionText.setText("Button 1 Active");
} else {
positionText.setText("");
}
break;
case BUTTON2:
if (pinState == 1) {
positionText.setText("Button 2 Active");
} else {
positionText.setText("");
}
break;
default:
break;
}
}
};
InputAction action = new InputAction();
post(action);
}
});
}
public View getmButtonView() {
return mButtonView;
}
}
and another activity
package net.mitchtech.adb;
import java.io.IOException;
import net.mitchtech.adb.simpledigitalinput.R;
import org.microbridge.server.Server;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SimpleDigitalInputActivity extends Activity {
private final static String TAG = SimpleDigitalInputActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Server server = null;
try
{
server = new Server(4567);
server.start();
ButtonView buttonView = (ButtonView) findViewById(R.id.inputView);
buttonView.setServer(server);
} catch (IOException e)
{
Log.e(TAG, "Unable to start TCP server", e);
System.exit(-1);
}
}
}

Your call() function is declared in your activity, but you're trying to access it in your ButtonView class. Try moving it into ButtonView (copy & paste).

Related

"SinchClient not started" The main problem in android studio

I am facing this problem for the last two weeks. Can you help me why this problem occurs?
Error occur at this line allClient.callPhoneNumber("+16315192247");
Please check it. Every time it crashes.
package com.eureka.voicecallinapk;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import com.sinch.android.rtc.calling.CallListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String APP_KEY = "b7258284-f0dnd-4734-afec-210d387d****";
//i do it for security because i am posting here
public static final String APP_SECRET = "k76tOLgz+kSdKL7ULYsH**==";
public static final String ENVIRONMENT = "clientapi.sinch.com";
public Call call;
private TextView callState;
public SinchClient sinchClient;
private Button button;
private String callerId;
private String recipientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
callerId = intent.getStringExtra("callerId");
recipientId = intent.getStringExtra("recipientId");
sinchClient = Sinch.getSinchClientBuilder()
.context(MainActivity.this)
.userId("172976")
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
// sinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
button = findViewById(R.id.button);
callState = findViewById(R.id.callState);
button.setOnClickListener(view -> {
if (call == null) {
try {
boolean s=isStarted();
Log.d("checksinch", String.valueOf(s));
CallClient callClient = sinchClient.getCallClient();
callClient.callPhoneNumber("+16315192247"); // Error occur at this line "SinchClient not started"
//callClient.callPhoneNumber("+16315192247");
// call = sinchClient.getCallClient().callPhoneNumber("+46000000000.");
// call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}catch (Exception e){
Log.d("checksinch", e.getMessage());
}
} else {
call.hangup();
button.setText("Call");
}
});
}
private boolean isStarted() {
return (sinchClient != null && sinchClient.isStarted());
}
private class SinchCallListener implements CallListener {
#Override
public void onCallEnded(Call endedCall) {
call = null;
SinchError a = endedCall.getDetails().getError();
button.setText("Call");
callState.setText("");
setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
}
#Override
public void onCallEstablished(Call establishedCall) {
callState.setText("connected");
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
#Override
public void onCallProgressing(Call progressingCall) {
callState.setText("ringing");
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call incomingCall) {
call = incomingCall;
Toast.makeText(MainActivity.this, "incoming call", Toast.LENGTH_SHORT).show();
call.answer();
call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}
}
}

android project compiles but doesn't run correctly

this is the main activity file That I have:
package de.project.packagelist;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import de.project.packagelist.models.Pkg;
public class MainActivity extends AppCompatActivity {
public static MainActivity instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
setContentView(R.layout.activity_main);
populatePackages();
}
public void onPackageUninstalled(String pkgName) {
Toast.makeText(this, pkgName + " is uninstalled", Toast.LENGTH_SHORT).show();
populatePackages();
}
public void onPackageInstalled(String pkgName) {
Toast.makeText(this, pkgName + " is installed", Toast.LENGTH_SHORT).show();
populatePackages();
}
public void onPackageChanged(String pkgName) {
Toast.makeText(this, pkgName + " is changed", Toast.LENGTH_SHORT).show();
populatePackages();
}
public void populatePackages() {
ArrayList<Pkg> pkgList = new ArrayList<>();
PackageListAdapter packageListAdapter = new PackageListAdapter(this, pkgList);
ListView listView = (ListView) findViewById(R.id.package_list);
listView.setAdapter(packageListAdapter);
pkgList.clear();
PackageManager pm = getPackageManager();
List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_META_DATA);
for (PackageInfo packageInfo : packages) {
pkgList.add(new Pkg(packageInfo.packageName, packageInfo.packageName, packageInfo.versionName, packageInfo.versionCode));
}
}
class PackageListAdapter extends ArrayAdapter<Pkg> {
public PackageListAdapter(Context context, List<Pkg> packages) {
super(context, R.layout.list_item_package, packages);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item_package, null);
}
final Pkg p = getItem(position);
if (p != null) {
TextView tt1 = (TextView)v.findViewById(R.id.pkg_label);
tt1.setText(p.getLabel());
TextView tt2 = (TextView)v.findViewById(R.id.pkg_name);
tt2.setText(p.getName());
TextView tt3 = (TextView)v.findViewById(R.id.pkg_version);
tt3.setText(p.getVersionName());
Button btn1 = (Button)v.findViewById(R.id.pkg_uninstall);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Uninstalling package: " + p.getName(), Toast.LENGTH_SHORT).show();
}
});
Button btn2 = (Button)v.findViewById(R.id.pkg_launch);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Launching package: " + p.getName(), Toast.LENGTH_SHORT).show();
}
});
ImageView imageView = (ImageView)v.findViewById(R.id.pkg_icon);
// imageView.setImageDrawable(p.get);
}
return v;
}
}
}
and this is the receiver's code:
import android.net.Uri;
import de.project.packagelist.MainActivity;
public class PackageChangedBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//triggered whenever any change happens to any package
//should inform activity
Uri data = intent.getData();
String pkgName = data.toString().substring(data.getScheme().length() + 1); //remove 'package:'
if(MainActivity.instance != null) {
if(intent.getAction() == "android.intent.action.PACKAGE_ADDED") {
MainActivity.instance.onPackageInstalled(pkgName);
} else if(intent.getAction() == "android.intent.action.PACKAGE_REMOVED") {
MainActivity.instance.onPackageUninstalled(pkgName);
} else if(intent.getAction() == "android.intent.action.PACKAGE_CHANGED") {
MainActivity.instance.onPackageChanged(pkgName);
}
}
}
}
MY code compiles without errors but when I run it, it takes too long to launch and the buttons are irresponsive. I know I am using older versions and libraries but do you see anything I can improve within my code. in my XML files(manifest and layouts, I have the launch icon and 2 buttons one to launch the package and the other one is to uninstall it.
What am I doing wrong?
I think you have to change your populatePackages function. You create your adapter and set your list view again and again on each brodcast process.
I think you should create a function which is initAdapter
InitAdapter function :
public void initAdapter(){
//not set list here and PackageListAdapter define as global
packageListAdapter = new PackageListAdapter(this);
ListView listView = (ListView) findViewById(R.id.package_list);
listView.setAdapter(packageListAdapter);
}
change the constructor of adapter class and create a setItems function
public PackageListAdapter(Context context) {
super(context, R.layout.list_item_package);
}
public setItems(List<Pkg> packages) {
this.packages = packages
}
and in your populatePackages function:
public void populatePackages() {
ArrayList<Pkg> pkgList = new ArrayList<>();
PackageManager pm = getPackageManager();
List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_META_DATA);
for (PackageInfo packageInfo : packages) {
pkgList.add(new Pkg(packageInfo.packageName, packageInfo.packageName, packageInfo.versionName, packageInfo.versionCode));
}
packageListAdapter.setItems(pkgList);
}

Saripaar Validation library throws No rules found error

I'm trying to use Saripaar Validation on my project, but it's throwing the following error:
java.lang.IllegalStateException: No rules found. You must have at
least one rule to validate. If you are using custom annotations, make
sure that you have registered them using the 'Validator.register()'
method.
My architecture separates the responsibility for handling the view into a class, for example for LoginActivity I have LoginView, which is where I handle my view logic like ButterKnife injection, event listening, etc. In this class I have my annotated fields.My LoginView looks like this:
import android.content.res.ColorStateList;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.ImageViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.serti.android.feenicia.validatortest.R;
import com.serti.android.feenicia.validatortest.screen.login.LoginActivity;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.subjects.PublishSubject;
public class LoginView implements Validator.ValidationListener {
public static final String LOGIN_ACTION = "LOGIN";
#BindView(R.id.login_button)
Button loginButton;
#BindView(R.id.username_edittext)
#NotEmpty
#Email
AppCompatEditText usernameEditText;
#BindView(R.id.password_edittext)
#Password(min = 8, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
AppCompatEditText passwordEditText;
#BindView(R.id.eye_imageview)
ImageView eyeImageView;
#BindView(R.id.loading_progressbar)
ProgressBar loadingProgressBar;
private boolean passwordIsVisible;
private AlertDialog confirmPaymentDialog;
private LoginActivity context;
private View rootView;
private PublishSubject<String> clickSubject = PublishSubject.create();
Validator validator;
public LoginView(LoginActivity context){
this.context = context;
FrameLayout parent = new FrameLayout(context);
parent.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
rootView = LayoutInflater.from(context).inflate(R.layout.activity_login, parent, true);
ButterKnife.bind(this, rootView);
validator = new Validator(context);
validator.setValidationListener(this);
eyeImageView.setOnClickListener(v -> handleClick(v.getId()));
loginButton.setOnClickListener(v -> handleClick(v.getId()));
passwordIsVisible = false;
}
#Override
public void onValidationSucceeded() {
String action = null;
Snackbar.make(rootView, "Validated", Snackbar.LENGTH_LONG).show();
loginButton.setVisibility(View.GONE);
loadingProgressBar.setVisibility(View.VISIBLE);
action = LOGIN_ACTION;
if(action != null){
clickSubject.onNext(action);
}
}
#Override
public void onValidationFailed(List<ValidationError> errors) {
for(ValidationError error : errors){
View view = error.getView();
String message = error.getCollatedErrorMessage(context);
if(view instanceof AppCompatEditText){
((AppCompatEditText) view).setError(message);
} else {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
}
}
public String getUserName(){
return usernameEditText.getText().toString();
}
public String getPassword(){
return passwordEditText.getText().toString();
}
private void handleClick(int id){
String action = null;
switch (id){
case R.id.login_button:
validator.validate();
break;
case R.id.eye_imageview:
togglePasswordVisibility();
}
}
private void togglePasswordVisibility(){
int color = 0;
if(passwordIsVisible){
passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
// eyeImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.eye_white));
color = ContextCompat.getColor(context, R.color.dark_blue_button);
ImageViewCompat.setImageTintList(eyeImageView, ColorStateList.valueOf(color));
}else{
passwordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
// eyeImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.eye_white));
color = ContextCompat.getColor(context, R.color.dark_gray);
}
ImageViewCompat.setImageTintList(eyeImageView, ColorStateList.valueOf(color));
passwordIsVisible = !passwordIsVisible;
passwordEditText.setSelection(passwordEditText.getText().length());
}
private void showIncompleteCredentialsMessage() {
Snackbar.make(loginButton, context.getText(R.string.incomplete_credentials_title), Snackbar.LENGTH_LONG).show();
}
public View getView(){
return rootView;
}
public Observable<String> observeClicks(){
return clickSubject;
}
public void openMainScreen(){
context.startMainActivity();
}
public void openSearchTicketsScreen() {
context.startSearchTicketsActivity();
}
public void showWrongCredentialsMessage() {
loginButton.setVisibility(View.VISIBLE);
loadingProgressBar.setVisibility(View.GONE);
Snackbar.make(loginButton, context.getText(R.string.wrong_credentials_title), Snackbar.LENGTH_LONG).show();
}
public void setContext(LoginActivity context) {
this.context = context;
}
}
From what I'm guessing, the library is trying to find these fields on my Activity, and since they're not there, then it's throwing this error.
Is there a way use this library accordingly to the architecture I'm handling?
use validator = new Validator(this) in place of validator = new Validator(context);

App enters infinite loop trying to connect to HC-06, but no loop is present

My application enters an infinite loop when I press the Connect button to connect to an HC-06 Bluetooth module (Arduino shield). However, there are no loops anywhere in the code when the button is pressed.
package dleedesign.dubcommunicationstestapp;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.Set;
/**
* Created by Chris on 7/24/2016.
*/
public class FirstFragment extends Fragment {
View myView;
public final String TAG = "Main";
private Bluetooth bt;
public Button sendCommand;
public Button send;
public TextView msgReceived;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.first_layout, container, false);
sendCommand = (Button) myView.findViewById(R.id.sendCommand);
sendCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
connectService();
}
});
send = (Button) myView.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBtCommand("1");
}
});
msgReceived = (TextView) myView.findViewById(R.id.msgReceived);
msgReceived.setText("Ready to connect");
bt = new Bluetooth(new MainActivity(), mHandler);
return myView;
}
public void sendBtCommand(String msg)
{
bt.sendMessage(msg);
}
public void connectService()
{
try {
msgReceived.setText("Connecting...");
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter.isEnabled())
{
bt.start();
bt.connectDevice("HC-06");
Log.d(TAG, "Btservice started- listening");
msgReceived.setText("Connected!");
}
else
{
Log.w(TAG, "Btservice started - bluetooth is not enabled, requesting enable...");
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
msgReceived.setText("Bluetooth not enabled, requested for enable");
}
} catch (Exception e) {
Log.e(TAG, "Unable to start bluetooth", e);
msgReceived.setText("Unable to connect: " + e);
}
}
private final Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case Bluetooth.MESSAGE_STATE_CHANGE:
Log.d(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
break;
case Bluetooth.MESSAGE_WRITE:
Log.d(TAG, "MESSAGE_WRITE");
break;
case Bluetooth.MESSAGE_READ:
Log.d(TAG, "MESSAGE_READ");
break;
case Bluetooth.MESSAGE_DEVICE_NAME:
Log.d(TAG, "MESSAGE_DEVICE_NAME " + msg);
break;
case Bluetooth.MESSAGE_TOAST:
Log.d(TAG, "MESSAGE_TOAST " + msg);
break;
}
}
};
}
For some reason, this problem just suddenly appeared when I tried to employ a loop to keep trying to connect while the connection is not established. I removed that code, but could it still be there somewhere?
Have you overridden the fragment's onActivityResult method?
If not, try overriding it and calling connectService() inside of it, by adding this to your fragment:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
connectService()
}

Calling activitygroup from customlistadapter

I am working on an android app which is having functionality of tabs.
Everything is working fine but I am not able to call activtygroup from listadapter.
Here is my code for list adapter:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.socialgoal.R;
import com.tv.socialgoal.imageloader.ImageLoader;
public class AllyListAdapter extends BaseAdapter{
Activity ctx;
ArrayList<Object> alist;
private ImageLoader imageLoader;
AllyBean allyBean;
private String photoPath;
public AllyListAdapter(Activity ctx, ArrayList<Object> alist) {
super();
this.ctx = ctx;
this.alist = alist;
imageLoader=new ImageLoader(ctx);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return alist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
LayoutInflater linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
View v=linf.inflate(R.layout.ally_list_row, null);
TextView tv=(TextView)v.findViewById(R.id.allyName);
ImageView profileImage=(ImageView)v.findViewById(R.id.ally_image);
Button inviteBtn=(Button)v.findViewById(R.id.invite_btn);
//SHOW DATA FROM LIST
allyBean=(AllyBean)alist.get(position);
tv.setText(allyBean.getName());
photoPath=allyBean.getAvatar();
profileImage.setTag(photoPath);
imageLoader.displayImage(photoPath, ctx, profileImage, false);
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
});
return v;
}
/*public void replaceContentView(String id, Intent newIntent) {
View view =getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}*/
}
Now I have to call AddRemoveFriends activtygroup.
Here is the code for activtygroup:
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.tv.servercommunication.IServerResponse;
import com.tv.servercommunication.WebServiceCommunicator;
import com.tv.socialgoal.Constant;
import com.tv.socialgoal.R;
import com.tv.socialgoal.network.NetworkAvailablity;
import com.tv.task.TabViewActivity;
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse{
Button backBtn;
Button addRemoveFriendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_profile_screen);
backBtn=(Button)findViewById(R.id.back_button);
addRemoveFriendBtn=(Button)findViewById(R.id.add_remove_frnd_btn);
backBtn.setOnClickListener(this);
addRemoveFriendBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_button:
break;
case R.id.add_remove_frnd_btn:
callAddFriend_WS();
break;
default:
break;
}
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case Constant.PID_ADD_REMOVE_FRIEND:
if (parseResponse(msg.obj.toString()) == true) {
Intent intent = new Intent(getParent(),
TabViewActivity.class);
startActivity(intent);
} else {
runOnUiThread(new Runnable() {
public void run() {
Constant.showAlertDialog(
Constant.DIALOG_TITLE_ERROR,
"Invalid username or password.",
getParent(), false);
}
});
}
break;
default:
break;
}
}
};
// GET USER ACCESSTOCKEN AND USER ID
private boolean parseResponse(String response) {
String message = null;
JSONObject post;
boolean isUserInfoAvail = false;
try {
JSONObject postjsonObject = new JSONObject(response);
JSONObject posts = postjsonObject.getJSONObject("posts");
post = posts.getJSONObject("post");
message = post.getString("message");
if (message.equalsIgnoreCase("failure")) {
isUserInfoAvail = false;
} else {
isUserInfoAvail = true;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return isUserInfoAvail;
}
public void callAddFriend_WS() {
if (NetworkAvailablity.checkNetworkStatus(AddRemoveFriendScreen.this)) {
// PREPARE URL
Constant.methodURL = "http://admin.tvdevphp.com/goalmachine/add_friend.php";
// PREPARE REQUEST PARAMETER
ArrayList<NameValuePair> requestParaList = new ArrayList<NameValuePair>();
requestParaList.add(new BasicNameValuePair("self_user_id", "1"));
requestParaList.add(new BasicNameValuePair("user_friend_id", "2"));
// CALL WEBSERVICE
WebServiceCommunicator.getInstance().registerForServerResponse(
AddRemoveFriendScreen.this);
WebServiceCommunicator.getInstance().callGetAppWebService(
Constant.showDialog, getParent(),
Constant.methodURL, getParent(), Constant.PID_ADD_REMOVE_FRIEND,
false, requestParaList);
} else {
Constant.showAlertDialog(Constant.errorTitle,
Constant.MSG_CHECK_INTERNET_SETTING, getParent(),
false);
}
}
// SERVER RESPONSE METHOD
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
}
Please suggest me how to call activtygroup from listadapter.
Make it like this you can access everything by doing like this.
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
}
class AllyListAdapter extends BaseAdapter
{
//Now you can call everything from ActivityGroup
}
}
Hope this will help you.
According to the android developper reference, you may use Fragments.
ActivityGroup is deprecated. Use the new Fragment and FragmentManager APIs instead; these are also available on older platforms through the Android compatibility package.
You can try this trick.
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(ctx instanceof ActivityGroup){
Intent intent = new Intent(ctx.getParent(),AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.getParent().startActivity(intent);
}
else{
Intent intent = new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
}
});
If it doesn't work just use internal class for your adapter in your AddRemoveFriendScreen class.

Categories

Resources