I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.
Related
I am trying to create an android application which acts as a Web Socket server. Here is my MainActivity.java.
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.http.conn.util.InetAddressUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText port, msg;
Button listen, send;
TextView status;
int p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
port = (EditText)findViewById(R.id.editText1);
msg = (EditText)findViewById(R.id.editText2);
listen = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String temp = port.getText().toString();
p = Integer.parseInt(temp);
try
{
custom_web_socket wsocket = new custom_web_socket(p);
wsocket.start();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class custom_web_socket extends WebSocketServer
{
public custom_web_socket(int port_add) throws UnknownHostException {
super(new InetSocketAddress(port_add));
// pass
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
status.setText("Connection closed.");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
status.setText((CharSequence) arg1);
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Connected");
}
}
}
When I run the program, the application starts. However, wheneve I try to enter value into the EditText field, the application hangs and ends. I am referring this example for web sockets - https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ChatServer.java
I have imported the necessary jar file. This is my first attempt at android programming and I am not sure what the problem could be.
You are using an event onClick.
So whenever you are trying to type something , it calls your method. and hangs up.
your action should happen when user finished typing the code.
You can use following code
port.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent
event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode()==KeyEvent.KEYCODE_ENTER)
{
if (!event.isShiftPressed()) {
// the user is done typing.
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
Also , refer to http://developer.android.com/reference/android/widget/EditText.html
you will get the clear idea.
i'm developing a simple application on android studio. I'm using "application", "observable", and many more. i got some error like this:
java.lang.RuntimeException: Unable to start activity ComponentInfo{id.wdharmana.doahindu/id.wdharmana.doahindu.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to id.wdharmana.doahindu.app.DoaApplication
2nd error
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to id.wdharmana.doahindu.app.DoaApplication
3rd error
at id.wdharmana.doahindu.MainActivity.onCreate(MainActivity.java:52)
This is my full MainActivity.java:
package id.wdharmana.doahindu;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import id.wdharmana.doahindu.adapter.ListJudulAdapter;
import id.wdharmana.doahindu.app.DoaApplication;
import id.wdharmana.doahindu.data.DefaultData;
import id.wdharmana.doahindu.helper.DoaHelper;
import id.wdharmana.doahindu.model.DoaModel;
import id.wdharmana.doahindu.model.DoaObserver;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
public class MainActivity extends AppCompatActivity implements Observer {
private ListView lvJudul;
private ArrayList<DoaModel> listJudul;
private DoaHelper doaHelper;
public ListJudulAdapter listJudulAdapter;
private DoaApplication application;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvJudul = (ListView)findViewById(R.id.lvListJudul);
listJudul = new ArrayList<DoaModel>();
application = (DoaApplication) getApplication();
application.getDoaObserver().addObserver(this);
doaHelper = new DoaHelper(MainActivity.this);
doaHelper.open();
listJudul = doaHelper.getAllData();
if (listJudul.size()>0) {
bindData();
}else{
insertDefaultData();
}
lvJudul.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
showMeaningDialog(MainActivity.this, listJudul.get(arg2));
}
});
lvJudul.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
deleteDialog(listJudul.get(arg2).getId());
return false;
}
});
}
private void insertDefaultData() {
// TODO Auto-generated method stub
new StoreDefaultData().execute();
}
public void update(Observable observable, Object o) {
if (o.equals(DoaObserver.NEED_TO_REFRESH)){
bindData();
}
}
private class StoreDefaultData extends AsyncTask<Void, Void, Void>{
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle(getString(R.string.notify_input_data));
mProgressDialog.setMessage(getString(R.string.text_please_wait));
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < DefaultData.defaultData.length; i++) {
doaHelper.insert(DoaModel.getDoaModel(DefaultData.defaultData[i][0],
DefaultData.defaultData[i][1]));
}
listJudul = doaHelper.getAllData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
listJudulAdapter = new ListJudulAdapter(MainActivity.this, listJudul);
lvJudul.setAdapter(listJudulAdapter);
}
}
#Override
protected void onDestroy() {
if (doaHelper != null){
doaHelper.close();
}
super.onDestroy();
}
public static void showMeaningDialog(final Activity activity, final DoaModel item) {
final Dialog dialog = new Dialog(activity, R.style.AppCompatAlertDialogStyle);
dialog.setContentView(R.layout.dialog_konten);
dialog.setCancelable(true);
TextView txtKonten = (TextView)dialog.findViewById(R.id.txtMeaning);
TextView txtJudul = (TextView)dialog.findViewById(R.id.txtWord);
Button btnTutup = (Button)dialog.findViewById(R.id.btnTutup);
Button btnEdit = (Button)dialog.findViewById(R.id.btnEdit);
txtKonten.setText(item.getKonten());
txtJudul.setText(item.getJudul());
btnEdit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//FormInputUpdateActivity.toFormInputUpdate(activity, item);
dialog.dismiss();
}
});
btnTutup.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
private void deleteDialog(final int id) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(MainActivity.this, R.style.AppCompatAlertDialogStyle);
dialog.setTitle("Hapus");
//dialog.setContentView(R.layout.dialog_delete);
dialog.setCancelable(true);
// Button btnYes = (Button)dialog.findViewById(R.id.btnDeleteYes);
// Button btnCancel = (Button)dialog.findViewById(R.id.btnDeleteCancel);
// btnYes.setOnClickListener(new OnClickListener() {
// public void onClick(View v) {
// // TODO Auto-generated method stub
// doaHelper.delete(id);
// dialog.dismiss();
// Toast.makeText(MainActivity.this, getString(R.string.text_success_delete), Toast.LENGTH_LONG).show();
// application.getDoaObserver().refresh();
// }
// });
//btnCancel.setOnClickListener(new View.OnClickListener() {
// public void onClick(View arg0) {
// TODO Auto-generated method stub
// dialog.dismiss();
// }
//});
dialog.show();
}
public void bindData(){
if (listJudul.size()>0) {
listJudul.clear();
}
listJudul = doaHelper.getAllData();
listJudulAdapter = new ListJudulAdapter(MainActivity.this, listJudul);
lvJudul.setAdapter(listJudulAdapter);
listJudulAdapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
}
This is DoaApplication.java
package id.wdharmana.doahindu.app;
import android.app.Application;
import id.wdharmana.doahindu.model.DoaObserver;
/**
* Created by WDHARMANA on 9/18/2015.
*/
public class DoaApplication extends Application {
DoaObserver doaObserver;
#Override
public void onCreate() {
super.onCreate();
doaObserver = new DoaObserver();
}
public DoaObserver getDoaObserver(){
return doaObserver;
}
}
No error when build. Please tell me if you have some suggestions. Thanks in advance.
Put DoaApplication in your manifest, in the <application> node as android:name="id.wdharmana.doahindu.app.DoaApplication"
Please make sure your AndroidManifest.xml like that:
<application
android:name="id.wdharmana.doahindu.app.DoaApplication"
... >
...
</application>
I think you forgot to add your
I was trying to run some test on SurfaceViewer with SurfaceViewer having its own thread and everything worked just fine. Then I changed my code to change orientation of screen using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
In the code below: I have an activity which uses Fragments. I have another class which extends SurfaceView class. Problem starts when I add setRequestedOrientation. After I add setRequestedOrientation. Value of running at in FastRender Class run method is always false. If I comment line with setRequestedOrientation , it runs fines.
package com.example.testpractise;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class SurfaceViewTest extends ActionBarActivity {
static int counter;
static {
Log.i("Intializing class Surface Test","counter");
System.out.println("Statrting here");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
counter++;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
counter++;
Log.i("Counter vlase",String.valueOf(counter));
System.out.println("value of counter"+counter);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_surface_view_test);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.surface_view_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
FastRenderView renderView;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(
// R.layout.fragment_surface_view_test, container, false);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BitmapCollection.initializeBitMapCollection(getActivity());
renderView = new FastRenderView(getActivity());
return renderView;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
renderView.resume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
renderView.pause();
}
static class FastRenderView extends SurfaceView implements Runnable {
Thread renderThread = null;
SurfaceHolder holder;
static volatile boolean running = false;
int x=0;
int y=0;
public FastRenderView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
public void pause()
{
running = false;
while(true)
{
try{
renderThread.join();
}catch (InterruptedException i){
}
}
}
public void resume()
{
running = true;
renderThread = new Thread(this);
renderThread.setName("RendererThread");
renderThread.start();
running=true;
}
#Override
public void run() {
// TODO Auto-generated method stub
int sleepCounter=0;
while(!running)
{
try {
if(sleepCounter <5)
{
sleepCounter++;
Thread.sleep(5000);
}else{
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while(running)
{
if(!holder.getSurface().isValid())
{
continue;
}
Canvas canvas=holder.lockCanvas();
canvas.drawRGB(255, 0, 0);
holder.unlockCanvasAndPost(canvas);
}
}
}
}
}
Sorry if my question doesn't match the format. This is my first time. Any pointers on what is wrong and why would be greatly appreciated.
Thanks
If you just want to lock the Activity to landscape, you can do it in Manifest by adding the android:screenOrientation="landscape" attribute to the activity element.
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.
I am using a thread and a handler in android. The app works fine as long as i dont any function from outside the activity. But if i call some funcyion from outside the activity from inside a thread, it gives NullPointerException.
package com.prog;
import com.API.TextBoxCheck;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ProgressBarExample extends Activity {
private Handler handler = new Handler();
int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
TextView tv=(TextView)findViewById(R.id.textView1);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread thread = new Thread(null, doBackgroundThreadProcessing,
"Background");
thread.start();
}});
Button stopBtn=(Button)findViewById(R.id.button2);
stopBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
try {
backgroundThreadProcessing();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private void backgroundThreadProcessing() throws InterruptedException {
TextView tv=(TextView)findViewById(R.id.textView1);
i=0;
while(i<100)
{
handler.post(doUpdateGUI);
Thread.sleep(50);
i++;
}
EditText et=(EditText)findViewById(R.id.editText1);
TextBoxCheck tbc = new com.API.TextBoxCheck();
String reply=tbc.TextBoxChecker(et.getText().toString(),10);
Log.d("thread", reply);
}
private Runnable doUpdateGUI = new Runnable() {
public void run() {
updateGUI();
}
private void updateGUI() {
// TODO Auto-generated method stub
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText(i+"%");
}
};
}
I have left out the code of textBoxCheck becoz i think it may be unnecesarry here.
Please help me on this.
PS. : I also tried using AsyncTask but the same problem occurs.
You are not on UI thread. You must be on UI thread to operate on any UI items. Create a handler on the UI thread and call your backgroundThreadProcessing(); from the handler and not from a non-UI thread.