How to create dummy view to anchor popup window android - java

I have the following situation:
private void startConnection() {
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("email","email#example.com");
String URL = "192.168.1.2/test.php";
Db_connection db = new Db_connection(hm,URL,context);
db.startTest();
}
public class Db_connection {
private HashMap<String, String> params;
private String URL;
private ConnectionController CC;
private ToolTip tt;
private Context con;
private ProgressDialog dialog;
public Db_connection(HashMap<String,String> params,String URL,Context con) {
this.params = params;
this.URL = URL;
this.con = con;
this.dialog = new ProgressDialog(con);
this.dialog.setCancelable(true);
this.CC = ConnectionController.getInstance();
}
public void startTest() {
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (dialog.isShowing()) { dialog.dismiss(); }
if (response != null && response.has("result")) {
try {
if (!response.getString("result").matches("error")) {
Toast.makeText(con, "Response: "+response.getString("result"), Toast.LENGTH_LONG).show();
}
else { Toast.makeText(con, response.getString("errmsg"), Toast.LENGTH_LONG).show(); return; }
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToolTip tt = new ToolTip(con, error.getMessage());
tt.showNow();
Log.e("Error: ", error.getMessage());
}
});
req.setRetryPolicy(rp);
CC.addToRequestQueue(req);
}
}
public class ToolTip {
private Context con;
private PopupWindow pn;
private View layout;
private ImageView cancel;
private TextView mess;
public ToolTip(Context con,String htmlMsg) {
this.con = con;
LayoutInflater inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.tooltip,null);
pn = new PopupWindow(layout,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,false);
pn.setAnimationStyle(R.style.AnimationToolTip);
cancel = (ImageView)layout.findViewById(R.id.tooltip_imageClose);
mess = (TextView)layout.findViewById(R.id.tooltip_mainText);
mess.setText(Html.fromHtml(htmlMsg));
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pn.dismiss();
}
});
}
public void showNow() {
pn.showAtLocation(/*HERE IS WHERE I DON'T KNOW WHAT TO PASS AS VIEW*/((Activity) con).getActionBar().getCustomView(), Gravity.NO_GRAVITY, 0, 180);
}
}
Everything works but when the volley request throws an error and uses the ToolTip class to show the error:
ToolTip tt = new ToolTip(con, error.getMessage());
tt.showNow();
i get this exception:
11-21 15:08:06.390: E/AndroidRuntime(22448): Process: com.tooltip.test, PID: 22448
11-21 15:08:06.390: E/AndroidRuntime(22448): java.lang.ClassCastException: com.tooltip.test.ConnectionController cannot be cast to android.app.Activity
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.tooltip.test.ToolTip.showNow(ToolTip.java:46)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.tooltip.test.Db_connection$2.onErrorResponse(Db_connection.java:100)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.volley.Request.deliverError(Request.java:577)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.os.Handler.handleCallback(Handler.java:733)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.os.Handler.dispatchMessage(Handler.java:95)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.os.Looper.loop(Looper.java:136)
11-21 15:08:06.390: E/AndroidRuntime(22448): at android.app.ActivityThread.main(ActivityThread.java:5139)
11-21 15:08:06.390: E/AndroidRuntime(22448): at java.lang.reflect.Method.invokeNative(Native Method)
11-21 15:08:06.390: E/AndroidRuntime(22448): at java.lang.reflect.Method.invoke(Method.java:515)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
11-21 15:08:06.390: E/AndroidRuntime(22448): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
11-21 15:08:06.390: E/AndroidRuntime(22448): at dalvik.system.NativeStart.main(Native Method)
Usually i pass this:
((Activity) con).getActionBar().getCustomView()
as the view to which anchor the popup window and it works but in this particular case, the activity calling the tooltip class, doesn't have an actionbar (it's the only one, all others activity does have the custom actionbar).
I'm here to ask if there is a method to use a dummy, programmatically created view to use in this case.
Or maybe i'm doing it wrong and you have a nice suggestion :)
Thanks in advance

After some try i finally came to a solution: i choose to use two different method, one for activity with action bar, and one for activity without action bar:
public void showNow() { //THIS IS FOR ACTIVITY WITH ACTION BAR
pn.showAtLocation((Activity)con.getActionBar().getCustomView(), Gravity.NO_GRAVITY, 0, 180);
}
public void showNowNoActBar() { //THIS IS FOR ACTIVITY WITHOUT ACTION BAR
pn.showAtLocation(con.findViewById(R.id.dummy_hidden_view), Gravity.NO_GRAVITY, 0, 180);
}
Obviously R.id.dummy_hidden_view is defined in the XML Layout of the activity without the custom action bar like this:
<TextView
android:id="#+id/dummy_hidden_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone" />
I think that both method could be solved with only one method but as of now, i can rely on my "double method" solution for what i need. Hope it helps someone else. Still remain the fact that i will appreciate any better suggestion on how to handle this.

Related

runOnUiThread: Cant touch the View, Exception

I know this has been posted multiple times now, but nothing seemed to fix my problem. I create a Loading Dialog on the UI thread, then start another thread which is doing some networking stuff and via interface, the class gets a callback, when networking is done. The problem is, after its done, i cant remove the loading dialog, even with "runOnUIThread". Here is the code:
public void onClickLoginButton (View view) {
if (!((EditText)findViewById(R.id.textNickname)).getText().toString().isEmpty() &&
!((EditText)findViewById(R.id.textPassword)).getText().toString().isEmpty()) {
loggingIn = new ProgressDialog(this);
loggingIn.setTitle("Login");
loggingIn.setMessage("Wait while logging in...");
loggingIn.show();
final LoginInterface callbackInterface = this;
new Thread(new Runnable() {
public void run() {
Networking net = new Networking();
net.Login(((EditText) findViewById(R.id.textNickname)).getText().toString(), ((EditText) findViewById(R.id.textPassword)).getText().toString(), callbackInterface);
}
}).start();
}
}
And this is the function that gets called by the networking stuff, after its done:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
loggingIn.hide();
loggingIn = null;
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
And this is the stack trace:
04-17 17:06:11.313 13018-13121/com.assigame.nidhoegger.assigame E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-1422
Process: com.assigame.nidhoegger.assigame, PID: 13018
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6122)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:850)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.setFlags(View.java:8908)
at android.view.View.setVisibility(View.java:6036)
at android.app.Dialog.hide(Dialog.java:299)
at com.assigame.nidhoegger.assigame.Login.LoginCallback(Login.java:72)
at com.assigame.nidhoegger.assigame.Networking.Login(Networking.java:134)
at com.assigame.nidhoegger.assigame.Login$1.run(Login.java:64)
at java.lang.Thread.run(Thread.java:841)
04-17 17:06:11.719 13018-13018/com.assigame.nidhoegger.assigame E/WindowManager﹕ android.view.WindowLeaked: Activity com.assigame.nidhoegger.assigame.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42284588 G.E..... R......D 0,0-684,324} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:366)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.assigame.nidhoegger.assigame.Login.onClickLoginButton(Login.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
You are calling the loggingIn.hide() method twice, and the first time not on the UI thread. Change your code to this:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}

Fatal Exception AsyncTask #2 what did I do wrong?

I have a php/mysql query working that looks up the VIN, if the VIN is in the database it returns "VIN already exists" Where did I screw up in this: Error report say Fatal Exception : AsyncTask #2 (I have code that actually works above this, problem started when I tried to rewrite this to run the php checkVin before launching the Sell page)
11-21 16:34:43.736: E/AndroidRuntime(725): FATAL EXCEPTION: AsyncTask #2
11-21 16:34:43.736: E/AndroidRuntime(725): java.lang.RuntimeException: An error occured while executing doInBackground()
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.lang.Thread.run(Thread.java:856)
11-21 16:34:43.736: E/AndroidRuntime(725): Caused by: java.lang.IllegalArgumentException: Host name may not be null
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:626)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.getServerResopnse(Scan.java:272)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.access$1(Scan.java:260)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:240)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:1)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-21 16:34:43.736: E/AndroidRuntime(725): ... 5 more
private void addSellButtonListener() {
Button sell = (Button) findViewById(R.id.sell_button);
sell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendDatatoServer();
}
});
}
private String formatDataAsJASON() {
JSONObject root = new JSONObject();
try {
root.put("User", userId.getText().toString());
root.put("Pword", userPass.getText().toString());
root.put("VIN", VINID.getText().toString());
return root.toString();
} catch (JSONException e) {
Log.d("JWP", "Can't format JSON");
}
return null;
}
private void sendDatatoServer() {
final String json = formatDataAsJASON();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
return getServerResopnse(json);
}
#Override
protected void onPostExecute(String result) {
if (result == "VIN already exists") {
Toast.makeText(Scan.this,
getString(R.string.vin_exists), Toast.LENGTH_LONG)
.show();
final Intent i = new Intent(Scan.this, Scan.class);
startActivity(i);
} else {
StartSell();
}
}
}.execute();
}
private String getServerResopnse(String json) {
HttpPost post = new HttpPost("http://" + serverIp.getText().toString()
+ "/chekVIN.php");
try {
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
return response;
} catch (UnsupportedEncodingException e) {
Log.d("JWP", e.toString());
} catch (ClientProtocolException e) {
Log.d("JWP", e.toString());
} catch (IOException e) {
Log.d("JWP", e.toString());
}
return null;
}
private void StartSell() {
final Intent i = new Intent(Scan.this, Sell.class);
EditText editText = (EditText) findViewById(R.id.VIN);
String text = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Make);
String text2 = editText2.getText().toString();
EditText editText3 = (EditText) findViewById(R.id.Model);
String text3 = editText3.getText().toString();
EditText editText4 = (EditText) findViewById(R.id.Color);
String text4 = editText4.getText().toString();
EditText editText5 = (EditText) findViewById(R.id.Year);
String text5 = editText5.getText().toString();
try {
FileOutputStream fos = openFileOutput(VinHolder,
Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
FileOutputStream fos2 = openFileOutput(MakeHolder,
Context.MODE_PRIVATE);
fos2.write(text2.getBytes());
fos2.close();
FileOutputStream fos3 = openFileOutput(ModelHolder,
Context.MODE_PRIVATE);
fos3.write(text3.getBytes());
fos3.close();
FileOutputStream fos4 = openFileOutput(ColorHolder,
Context.MODE_PRIVATE);
fos4.write(text4.getBytes());
fos4.close();
FileOutputStream fos5 = openFileOutput(YearHolder,
Context.MODE_PRIVATE);
fos5.write(text5.getBytes());
fos5.close();
}
catch (Exception e) {
Log.d("DEBUGTAG", "File Not Saved" + text);
e.printStackTrace();
}
startActivity(i);
}
Because I use a Text file from another page of the app to hold a manually entered ip address, I needed to carry that info over so that the the HttpPost("http://" +serverIp.getText().toString() + "chechvin.php"); would actually have the ip address in it.
After adding:
public static final String SERVERIP= "sinfo.txt";
everything worked just fine.

Android communication between activity and service

I'm trying to implement a system service on Android with inter-process communication based on binding a messenger. For this I'm following this tutorial:
http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html
But no matter what I'm trying, i can't get it to work.
I found different tutorials online but in the end they are all based on the same procedure.
The app will crash right away when I'm trying to communicate with the service.
Error message
10-09 15:40:33.490 3468-3468/com.example.stenosis.testservice E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.stenosis.testservice, PID: 3468
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stenosis.testservice/com.example.stenosis.testservice.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.stenosis.testservice.MyActivity.sendMsg(MyActivity.java:87)
at com.example.stenosis.testservice.MyActivity.onCreate(MyActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
MyActivity.java:
public class MyActivity extends Activity {
private ServiceConnection sConn;
private Messenger messenger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Service Connection to handle system callbacks
sConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We are conntected to the service
messenger = new Messenger(service);
}
};
// We bind to the service
bindService(new Intent(this, MyService.class), sConn, Context.BIND_AUTO_CREATE);
// Try to send a message to the service
sendMsg();
}
// This class handles the Service response
class ResponseHandler extends Handler {
#Override
public void handleMessage(Message msg) {
int respCode = msg.what;
String result = "";
switch (respCode) {
case MyService.TO_UPPER_CASE_RESPONSE: {
result = msg.getData().getString("respData");
System.out.println("result");
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
}
public void sendMsg() {
String val = "This is a test";
Message msg = Message
.obtain(null, MyService.TO_UPPER_CASE);
msg.replyTo = new Messenger(new ResponseHandler());
// We pass the value
Bundle b = new Bundle();
b.putString("data", val);
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
MyService.java
public class MyService extends Service {
public static final int TO_UPPER_CASE = 0;
public static final int TO_UPPER_CASE_RESPONSE = 1;
private Messenger msg = new Messenger(new ConvertHanlder());;
#Override
public IBinder onBind(Intent intent) {
return msg.getBinder();
}
class ConvertHanlder extends Handler {
#Override
public void handleMessage(Message msg) {
// This is the action
int msgType = msg.what;
switch (msgType) {
case TO_UPPER_CASE: {
try {
// Incoming data
String data = msg.getData().getString("data");
Message resp = Message.obtain(null, TO_UPPER_CASE_RESPONSE);
Bundle bResp = new Bundle();
bResp.putString("respData", data.toUpperCase());
resp.setData(bResp);
msg.replyTo.send(resp);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
}
default:
super.handleMessage(msg);
}
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:process=":convertprc"/>
Your problem is that the messanger property is null. You are experiencing concurrency problem. The bindService method is asynchronous - it returns immediately and performs the binding in a background thread. When the binding is done, the onServiceConnected method is invoked. When you try to send the message, the messanger is still not initialized because the onServiceConnected method is hasn't been executed yet.

Updating Listview ( SharedPreferences -> ArrayList) from separate Class

I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)

BadTokenException even after referring to Activity and not the application context

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.

Categories