Partage
  • Partager sur Facebook
  • Partager sur Twitter

[Android] Problème de Dialog Box

Erreur lors de l'apparation d'une Dialog Box depuis une autre classe

    31 mars 2013 à 15:41:33

    Bonjour à tous !

    Je suis entrain de développer une application Android avec une interaction client-serveur. Afin de prévenir l'utilisateur de certains problèmes, je souhaiterais faire apparaitre des Dialog Box personnalisée. Cependant, le problème que je rencontre actuellement, c'est que mes Dialog Box génère aléatoirement des erreurs lorsqu'elles apparaissent. Voici le code de mon activité, ainsi que celle de mes threads qui peuvent générer les DialogBox :

    package be.ac.ucl.lfsab1509.proxipoll;
    
    import java.io.IOException;
    import java.net.UnknownHostException;
    
    import be.ac.ucl.lfsab1509.proxipoll.client.Client;
    import be.ac.ucl.lfsab1509.proxipoll.client.Client.IPException;
    import be.ac.ucl.lfsab1509.proxipoll.controller.Controller;
    import be.ac.ucl.lfsab1509.proxipoll.model.Disconnection;
    import be.ac.ucl.lfsab1509.proxipoll.server.Server;
    import android.app.Activity;
    import android.app.Dialog;
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.net.NetworkInfo.State;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiManager;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.RadioButton;
    import android.widget.TextView;
    import android.widget.Button;
    
    public class ClientStateActivity extends Activity implements OnClickListener
    {
    	public Client client;
    	
    	public void onCreate(Bundle savedInstanceState)
    	{
    		super.onCreate(savedInstanceState);
    		this.setContentView(R.layout.activity_client_state);
    		((Button) this.findViewById(R.id.buttonback)).setOnClickListener(this);
    		
    		
    		// To run on the emulator
    //		client = new Client(Controller.getClientManager().getIp(), 1024, this);
    		
    		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    		if( wifi == NetworkInfo.State.CONNECTED  || wifi == NetworkInfo.State.CONNECTING )
    		{
    			client = new Client(Controller.getClientManager().getIp(), 1024, this);
    		}
    		else
    		{
    			showDialog(5);
    		}
    	}
    	
    	public Dialog onCreateDialog(int i)
    	{
    		Dialog box;
    		switch (i)
    		{
    			case 0:
    				return new ConnectionDialog(this, this);
    			case 1:
    				box = new ErrorConnectionDialog(this, this);
    				((TextView) box.findViewById(R.id.textView1)).setText("Unknown Host");
    				return box;
    			case 2:
    				box = new ErrorConnectionDialog(this, this);
    				((TextView) box.findViewById(R.id.textView1)).setText("Network Error");
    				return box;
    			case 3:
    				box = new ErrorConnectionDialog(this, this);
    				((TextView) box.findViewById(R.id.textView1)).setText("Wrong ip format");
    				return box;
    			case 4:
    				box = new ErrorConnectionDialog(this, this);
    				((TextView) box.findViewById(R.id.textView1)).setText("Wrong server name or password");
    				return box;
    			case 5:
    				box = new ErrorServerDialog(this, this);
    				return box;
    			case 6:
    				box = new ErrorConnectionDialog(this, this);
    				((TextView) box.findViewById(R.id.textView1)).setText("Something went wrong with the connection");
    				return box;
    			case 7:
    				box = new ErrorServerDialog(this, this);
    				((TextView) box.findViewById(R.id.textView1)).setText("Server was closed by host");
    				box.setTitle("Connection stopped");
    				client.disconnect();
    				return box;
    			default:
    				return null;
    		}
    	}
    	
    	@Override
    	public void onClick(View v) 
    	{
    		switch (v.getId()) 
    		{
    			case R.id.buttonback:
    				if(client != null)
    				{
    					try {
    						client.sendToServer(new Disconnection());
    					} catch (IOException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					client.disconnect();
    				}
    				finish();
    			break;
    		}
    	}
    }
    
    package be.ac.ucl.lfsab1509.proxipoll.client;
    
    import android.os.Looper;
    import be.ac.ucl.lfsab1509.proxipoll.ClientStateActivity;
    
    public class ServerChecker extends Thread
    {
    	private boolean flag;
    	ClientStateActivity activity;
    	
    	public ServerChecker(ClientStateActivity activity)
    	{
    		flag = false;
    		this.activity = activity;
    	}
    	
    	public synchronized void messageReceived()
    	{
    		flag = true;
    	}
    	
    	public synchronized void run()
    	{	
    		while(!Thread.currentThread().isInterrupted())
    		{
    			try {
    				wait(15000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			if(!flag)
    			{
    				activity.runOnUiThread(new Runnable() {
    					
    					@Override
    					public void run() {
    						activity.showDialog(6);
    					}
    				});
    			}
    			flag = false;
    		}
    	}
    }
    
    package be.ac.ucl.lfsab1509.proxipoll.client;
    
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OptionalDataException;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Hashtable;
    
    import android.os.Looper;
    import android.view.View;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.ScrollView;
    import android.widget.TextView;
    import be.ac.ucl.lfsab1509.proxipoll.ClientStateActivity;
    import be.ac.ucl.lfsab1509.proxipoll.R;
    import be.ac.ucl.lfsab1509.proxipoll.controller.Controller;
    import be.ac.ucl.lfsab1509.proxipoll.model.Authentification;
    import be.ac.ucl.lfsab1509.proxipoll.model.AuthentificationAnswer;
    import be.ac.ucl.lfsab1509.proxipoll.model.Disconnection;
    import be.ac.ucl.lfsab1509.proxipoll.model.FinishPoll;
    import be.ac.ucl.lfsab1509.proxipoll.model.Poll;
    
    public class Client extends Thread
    {
    	private Socket s;
    	private String ip;
    	private int port;
    	private ClientStateActivity activity;
    	
    	private ObjectOutputStream out;
    	private ObjectInputStream in;
    	
    	private ServerChecker serverC;
    	
    	// Strings used for layout update when a poll is received
    	private String question;
    	private String answer;
    	
    	private Hashtable<Integer, LinearLayout> tabLayout;
    	
    	public Client(String ip, int port, ClientStateActivity activity)
    	{
    		this.ip = ip;
    		this.port = port;
    		this.activity = activity;
    		this.serverC = new ServerChecker(activity);
    		
    		tabLayout = new Hashtable<Integer, LinearLayout>();
    		
    		start();
    		serverC.start();
    	}
    	
    	private byte[] ipConvert(String ip) throws IPException
    	{
    		String[] tab = ip.split("\\.");
    		if(tab.length != 4)
    			throw new IPException();
    		System.out.println("Good size");
    		byte[] tabB = new byte[tab.length];
    		for(int i = 0 ; i < tabB.length ; i++)
    		{
    			try
    			{
    				int current = new Integer(tab[i]);
    				tabB[i] = (byte)current;
    			}
    			catch(NumberFormatException e)
    			{
    				throw new IPException();
    			}
    		}
    		return tabB;
    	}
    	
    	public class IPException extends Exception
    	{
    		public IPException()
    		{
    			super("IP does not have good representation : wrong size or wrong format");
    		}
    	}
    	
    	public class WrongAuthentification extends Exception
    	{
    		public WrongAuthentification()
    		{
    			super("Wrong Server Name or Password");
    		}
    	}
    	
    	public void run()
    	{
    		try 
    		{
    			s = new Socket(InetAddress.getByAddress(ipConvert(ip)), port);
    			out = new ObjectOutputStream(s.getOutputStream());
    			in = new ObjectInputStream(s.getInputStream());
    			System.out.println("ok1");
    		} 
    		catch (UnknownHostException e) 
    		{
    			System.out.println(e);
    			activity.runOnUiThread(new Runnable() {
    				
    				@Override
    				public void run() {
    					activity.showDialog(1);
    				}
    			});
    			return;
    		}
    		catch (IOException e) 
    		{
    			System.out.println(e);
    			activity.runOnUiThread(new Runnable() {
    				
    				@Override
    				public void run() {
    					activity.showDialog(2);
    				}
    			});
    			return;
    		} 
    		catch (IPException e) 
    		{
    			System.out.println(e);
    			activity.runOnUiThread(new Runnable() {
    				
    				@Override
    				public void run() {
    					activity.showDialog(3);
    				}
    			});
    			return;
    		}
    		
    		
    		System.out.println("Trying to send");
    		try {
    			this.sendToServer(new Authentification(Controller.getClientManager().serverName, Controller.getClientManager().passWord));
    			System.out.println("ok send");
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		
    		Object inputObject;
    		
    		try {
    			while(!Thread.currentThread().isInterrupted() && (inputObject = in.readObject()) != null)
    			{
    				serverC.messageReceived();
    				System.out.println("Object received");
    				if(inputObject instanceof AuthentificationAnswer)
    				{
    					AuthentificationAnswer authReceived = (AuthentificationAnswer) inputObject;
    					System.out.println("AuthentificationAnswer : "+authReceived.getSuccess());
    					if(!authReceived.getSuccess())
    					{
    						throw new WrongAuthentification();
    					}
    					if(!authReceived.getFreeMessage())
    					{
    						activity.runOnUiThread(new Runnable(){
    							@Override
    							public void run() {
    								((LinearLayout) activity.findViewById(R.id.main_layout)).removeView(activity.findViewById(R.id.layout_free_message));
    								((TextView) activity.findViewById(R.id.textText1)).setVisibility(View.VISIBLE);
    							}
    						});
    					}
    					else
    					{
    						((Button) activity.findViewById(R.id.button_send_free_message)).setOnClickListener(new FreeMessageSender((EditText) activity.findViewById(R.id.free_message_edittext), this));
    					}
    				}
    				else if(inputObject instanceof Poll)
    				{
    					final Poll pollReceived = (Poll) inputObject;
    					System.out.println("Poll Received");
    					/**
    					 * Il faut traiter ce qe tu veux faire quand tu reçois un sondage.
    					 * J'ai gardé la même activité, j'ai juste modifié son contenu 
    					 */
    					pollReceived.printPoll();
    					// TODO Change to get all the questions and handle errors (empty questions...)
    					activity.runOnUiThread(new Runnable() {
    
    			            @Override
    			            public void run() {
    			            	TextView title = new TextView(activity);
    			            	title.setText(pollReceived.name);
    			            	title.setTextSize(16);
    			            	
    			            	LinearLayout layout = new LinearLayout(activity);
    			            	layout.setOrientation(LinearLayout.VERTICAL);
    			            	layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    			            	layout.addView(title);
    			            	
    			            	tabLayout.put(pollReceived.id, layout);
    			            	
    			            	((LinearLayout) activity.findViewById(R.id.layout_poll)).addView(layout);
    			            	
    			            	Hashtable<Integer, Hashtable<String, View>> mem = new Hashtable<Integer, Hashtable<String, View>>();
    			            	
    			            	for(int i = 0 ; i < pollReceived.questions.size() ; i++)
    			            	{
    			            		TextView questionTitle  = new TextView(activity);
    			            		questionTitle.setText("Question "+(i+1)+" : "+pollReceived.questions.get(i).question);
    			            		questionTitle.setTextSize(12);
    			            		layout.addView(questionTitle);
    			            		
    			            		Hashtable<String, View> tempq = new Hashtable<String, View>();
    			            		mem.put(pollReceived.questions.get(i).id, tempq);
    			            		
    			            		switch(Math.abs(pollReceived.questions.get(i).type))
    			            		{
    			            			case 1:
    			            				for(int j = 0 ; j < pollReceived.questions.get(i).answers.size() ; j++)
    			            				{           					
    			            					CheckBox tempC = new CheckBox(activity);
    			            					tempC.setText(pollReceived.questions.get(i).answers.get(j).answer);
    			            					tempC.setTextSize(12);
    			            					tempq.put(pollReceived.questions.get(i).answers.get(j).answer, tempC);
    			            					layout.addView(tempC);
    			            				}
    			            			break;
    			            			case 2:
    			            				RadioGroup tempRG = new RadioGroup(activity);
    			            				tempRG.setOrientation(RadioGroup.VERTICAL);
    			            				layout.addView(tempRG);
    			            				for(int j = 0 ; j < pollReceived.questions.get(i).answers.size() ; j++)
    			            				{
    			            					RadioButton tempRB = new RadioButton(activity);
    			            					tempRB.setText(pollReceived.questions.get(i).answers.get(j).answer);
    			            					tempRB.setTextSize(12);
    			            					tempq.put(pollReceived.questions.get(i).answers.get(j).answer, tempRB);
    			            					tempRG.addView(tempRB);
    			            				}
    			            			break;
    			            			case 3:
    			            				EditText tempE = new EditText(activity);
    			            				tempE.setTextSize(12);
    			            				tempq.put("aucune question", tempE);
    			            				layout.addView(tempE);
    			            			break;
    			            		}
    			            	
    			            	}
    			            	
    			            	Button tempB = new Button(activity);
    			            	tempB.setText("Envoyer");
    			            	tempB.setOnClickListener(new PollAnswerSender(pollReceived.id, mem, activity, layout, tabLayout));
    			            	layout.addView(tempB);
    			            }
    			        });
    				}
    				else if(inputObject instanceof Integer)
    				{
    					this.sendToServer((Integer) inputObject);
    				}
    				else if(inputObject instanceof Disconnection)
    				{
    					activity.runOnUiThread(new Runnable() {
    						
    						@Override
    						public void run() {
    							activity.showDialog(7);
    						}
    					});
    					this.disconnect();
    				}
    				else if(inputObject instanceof FinishPoll)
    				{
    					final FinishPoll tempFP = (FinishPoll) inputObject;
    					activity.runOnUiThread(new Runnable(){
    						@Override
    						public void run() {
    							if(tabLayout.containsKey(tempFP.getId()))
    								((LinearLayout) activity.findViewById(R.id.layout_poll)).removeView(tabLayout.remove(tempFP.getId()));
    						}
    					});
    				}
    				/**
    				 * Rajouter d'autres else if pour tester s'il s'agit d'autres structures Reçu par le client !
    				 * Par exemple, si tu envoies un string, tu rajoutes, else if(inputObject instanceof String)
    				 * puis tu cast et tu traites ce que tu veux faire.
    				 * 
    				 * 
    				 */
    			}
    		} catch (OptionalDataException e) {
    			System.out.println("test error 1");
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			System.out.println("test error 2");
    			e.printStackTrace();
    		} catch (SocketException e) {
    			if(e.getCause() != null)
    			{
    				activity.runOnUiThread(new Runnable() {
    					
    					@Override
    					public void run() {
    						activity.showDialog(6);
    					}
    				});
    			}
    			e.printStackTrace();
    		} catch (EOFException e) {
    			activity.runOnUiThread(new Runnable() {
    			
    			@Override
    			public void run() {
    				activity.showDialog(7);
    			}
    			});
    			this.disconnect();
    			e.printStackTrace();
    	 	} catch (IOException e) {
    			System.out.println(e.getCause());
    			e.printStackTrace();
    		} catch (WrongAuthentification e) 
    		{
    			activity.runOnUiThread(new Runnable() {
    				
    				@Override
    				public void run() {
    					activity.showDialog(4);
    				}
    			});
    		}
    	}
    	
    	public void disconnect()
    	{
    		serverC.interrupt();
    		Thread.currentThread().interrupt();
    		try {
    			s.close();
    			out.close();
    			in.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
    		catch (NullPointerException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
    	}
    	
    	public synchronized void sendToServer(Object message) throws IOException
    	{
    		out.writeObject(message);
    	}
    }
    

    Quelqu'un aurait-il une idée de la méthode à suivre pour résoudre les problèmes qui apparaissent ?

    Merci d'avance :)



    • Partager sur Facebook
    • Partager sur Twitter

    [Android] Problème de Dialog Box

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown