Java: проблема с доступом к значению глобальной переменной - PullRequest
0 голосов
/ 01 февраля 2011

Пожалуйста, пройдите через код ниже.

String[] Info содержит 2 значения, подобные этому:

  • shiftDirection & 1 или
  • currGear & 5 и подобные пары,

Если я получу shiftDirection & 0, я должен отобразить ранее полученное значение currGear.

Итак, я создаю PresentGear как глобальную переменную, а когда получено currGear, я сохраняю ее значение в PresentGear.

Затем, когда я получаю shiftDirection & 0, я пытаюсь отобразить PresentGear, но ничего не отображается.

PresentGear не присвоено значение.Было бы очень полезно, если бы кто-то мог подсказать, почему это происходит, или если мой подход неверен, любезно предложите альтернативный способ.

Приветствия,

Мадху

public class Images extends Activity {
    /** Called when the activity is first created. */
    //LinearLayout mLinearLayout;
    //ImageView showImage;
    String PresentGear = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        

        Bundle extras = getIntent().getExtras();
        String[] Info = extras.getStringArray("MsgInfo");
        Log.d("TCP","in DA Images. Message name: " + Info[0] + ", value: " + Info[1]);
        if (Info[0].equals("currGear")) {   
            PresentGear = Info[1];
            setContentView(R.layout.image);
            TextView text_bottom = (TextView) findViewById(R.id.textView2);
            text_bottom.setText(Info[1]);
        }
        Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
        DataAction(Info[0], Info[1]);            
    }

    public void DataAction (String mName, String mVal)  {
        String _mName = mName;
        String _mVal = mVal;

        if (_mName.equals("shiftDirection") && _mVal.equals("1")) {
            setContentView(R.layout.image);
            //TextView text_top = (TextView) findViewById(R.id.textView1);
            ImageView showImage = (ImageView) findViewById(R.id.imageView1);            
            //text_bottom.setText(Info[1]);
            showImage.setImageResource(R.drawable.shift_up);            
        } else if (_mName.equals("shiftDirection") && _mVal.equals("-1")) {
            setContentView(R.layout.image);
            //TextView text_bottom = (TextView) findViewById(R.id.textView2);
            ImageView showImage = (ImageView) findViewById(R.id.imageView1);            
            //text_bottom.setText(Info[1]);
            showImage.setImageResource(R.drawable.shift_down);          
        } else if (_mName.equals("recomGear") && _mVal != null) {
            Integer msgValue = Integer.parseInt(_mVal);
            Integer CurrentGear = (msgValue) - 1;
            Log.d("TCP","in DA Images. Current gear: " + CurrentGear);
            String Gear = Integer.toString(CurrentGear);
            setContentView(R.layout.image);
            TextView text_top = (TextView) findViewById(R.id.textView1);
            TextView text_bottom = (TextView) findViewById(R.id.textView2);
            ImageView showImage = (ImageView) findViewById(R.id.imageView1);            
            showImage.setImageResource(R.drawable.shift_up);
            text_bottom.setText(Gear);
            text_top.setText(_mVal);
        //} //else if (_mName.equals("currGear") && _mVal != null) {
            //PresentGear = _mVal;          
            //Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
            //setContentView(R.layout.image);
            //TextView text_bottom = (TextView) findViewById(R.id.textView2);
            //text_bottom.setText(_mVal);                       
        } else if (_mName.equals("shiftDirection") && _mVal.equals("0")) {
            Log.d("TCP","in DA Images. Present gear: " + PresentGear);
            setContentView(R.layout.image);
            TextView text_bottom = (TextView) findViewById(R.id.textView2);
            TextView text_top = (TextView) findViewById(R.id.textView1);
            text_top.setText("Go on");  
            text_bottom.setText(PresentGear);           
        }

    }
}

Обновление:

Спасибо всем за ответ.Я опубликую часть, откуда я получаю массив строк.Это может быть не самый лучший код.Будем рады, если будут предложены какие-либо изменения.

public class TCPListen extends Activity implements TCPListener {
    private TextView mTitle;
    public String data[] = new String[2];
    public String PGear;

    /** Called when the activity is first created. */
     @Override  
         public void onCreate(Bundle savedInstanceState) {  
             super.onCreate(savedInstanceState);  
             //setContentView(R.layout.main);            

             // Set up the window layout
             requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
             setContentView(R.layout.main);
             getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

             // Set up the custom title
             mTitle = (TextView) findViewById(R.id.title_left_text);
             mTitle.setText(R.string.app_name);
             mTitle = (TextView) findViewById(R.id.title_right_text);

             //TcpServiceHandler handler=new TcpServiceHandler(this);  
             //handler.execute("192.168.62.23");  

             TcpServiceHandler handler = new TcpServiceHandler(this,this);  
             Thread th = new Thread(handler);  
             th.start(); 
     }          

         public String[] callCompleted(String source){ 
                Log.d("TCP", "Std parser " + source);
                //mTitle.setText(source);
                //String data[] = new String[2]; 

                //if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>"))  {           
                    Document doc = null;  
                    try{
                       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
                       DocumentBuilder db = dbf.newDocumentBuilder();  
                       doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));  
                       NodeList n = doc.getElementsByTagName("N");  
                       Node nd = n.item(0);  
                       String msgName = nd.getFirstChild().getNodeValue();  
                       NodeList n1 = doc.getElementsByTagName("V");  
                       Node nd1 = n1.item(0);  
                       String tmpVal = nd1.getFirstChild().getNodeValue();  
                       data[0] = msgName;  
                       data[1] = tmpVal; 
                       Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
                       actionOnData(data[0], data[1]);
                      }  
                    catch(Exception e){  
                    e.printStackTrace();  
                }
                Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
                return data;
                //} else Log.d("TCP", "Message in wrong format " + source);
                //mTitle.setText("Message in wrong format " + source);
                //return data;
            }


       //Function to display driver messages/images based on individual messages
         public void actionOnData(String name, String value) {
            String tempName = name;
            String tempVal = value;             

                if(tempName.equals("shiftDirection") && tempVal.equals("1"))    {
                    Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
                    //mTitle.setText("Change to next higher gear");
                    Intent myIntent = new Intent();
                    myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
                    myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
                    startActivity(myIntent); 
                    finish();
                } else if(tempName.equals("recomGear")) {
                    Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
                    //mTitle.setText("Drive like a man");                   
                    Intent myIntent = new Intent();
                    myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
                    myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
                    startActivity(myIntent);
                    finish();
                } else if(tempName.equals("shiftDirection") && tempVal.equals("-1"))    {
                    Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
                    //mTitle.setText("Change to next higher gear");
                    Intent myIntent = new Intent();
                    myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
                    myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
                    startActivity(myIntent); 
                    finish();
                } else if(tempName.equals("currGear"))  {
                    Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
                    //mTitle.setText("Change to next higher gear");
                    PGear = data[1];
                    Intent myIntent = new Intent();
                    myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
                    myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
                    startActivity(myIntent); 
                    //finish();
                } else if(tempName.equals("shiftDirection") && tempVal.equals("0")) {
                    Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
                    //mTitle.setText("Change to next higher gear");
                    data[1] = PGear;
                    Intent myIntent = new Intent();
                    myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
                    myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
                    startActivity(myIntent); 
                    finish();
                } else mTitle.setText("Just show something");
                //Log.d("TCP", "Just show an image");

            //}

         }
}

Фактически, в приведенном выше коде я временно решил проблему сохранения значения currGear и использования его в shiftDirection, 0.

Ответы [ 2 ]

1 голос
/ 01 февраля 2011

Значение PresentGear будет сохраняться только в течение жизни вашего Activity.Если ОС убьет ваш Activity, то значение будет потеряно.Вы должны поставить некоторые логины в onPause(), onStop() и onDestroy() и проверить, как работает жизненный цикл вашего приложения.Возможно, вам придется выписать значение от PresentGear до SharedPreferences в onPause() и прочитать результат в вашем onCreate().Проверьте эту ссылку для жизненного цикла:

1 голос
/ 01 февраля 2011

Звучит так, будто вы должны пройти этот код в отладчике и проверить, какие значения доставляются в это действие. Как вы создаете намерение, которое будет доставлено? (Я подозреваю, что либо Info[0] не "currGear", либо Info[1] - "", но может происходить что-то еще.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...