2017-01-12 5 views
-3

Так что я очень новичок в студии Android. Моя проблема относительно проста, конвертирует данные из текстового поля в целое. Цель этого int должна использоваться в условном выражении. Однако я не могу найти ответ, который работает. Вот где мой код, с которым у меня проблемы, есть.Преобразование текстового поля в int (для использования в условном заявлении)

public void saveMatchData (MenuItem item) {               
    //save button in my menu                   
    //creates a toast to notify that it has been pressed            

    Toast toast = Toast.makeText(getApplicationContext(), "Save button pressed", Toast.LENGTH_SHORT); 
     toast.show();                               
    // create an EditText for matchNumberInput               
    EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput);       
    //assign value of matchNumberET(Edit Text) to match number           
    EditText matchNumber = (EditText) matchNumberET.getText();          
//attempted to assign to an int                 
    int matchNumberValue = Integer.parseInt(matchNumber); 
//         error here^^^^^ 


    //same as abover just tried a different way that i read online          
    EditText teamNumberDT = (EditText) findViewById(R.id.teamNumberInput);        
    int teamNumber = Integer.parseInt(teamNumberDT.getText().toString());    

    int i;                        
    //i have an array for matchNumber values and teamNumber values          
    //they start empty and as of now still are               
    //                         
    for (i = 0, i <= matchNumberArray.size(), i++);{             
    if (matchNumberValue == matchNumberArray.get(i)){ 
    //  error here^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
     //I just want to compare the value of i position of the array with the  data from textfield         
     //code to add matchNumber if not already there            
    }                        

    //both of these different ways to do this give me errors          

    }                         
    if (teamNumberArray.get(i) == teamNumber) {  
    //error here^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

    //code to add teamNumber if not already there             
    }                         

    Is it a problem with the conversion of the textField to an int or is it the way im using it? Or is it a problem with my array/s? 

Вот мой код. Извините, это очень неряшливо. ` package com.example.garre.frcscouting13;

  import android.net.Uri; 
     import android.support.design.widget.TabLayout; 
     import android.support.v7.app.AppCompatActivity; 
     import android.support.v7.widget.Toolbar; 

     import android.support.v4.app.Fragment; 
     import android.support.v4.app.FragmentManager; 
     import android.support.v4.app.FragmentPagerAdapter; 
     import android.support.v4.view.ViewPager; 
     import android.os.Bundle; 
     import android.view.LayoutInflater; 
     import android.view.Menu; 
     import android.view.MenuItem; 
     import android.view.View; 
     import android.view.ViewGroup; 
     import android.widget.ArrayAdapter; 
     import android.widget.Button; 
     import android.widget.EditText; 
     import android.widget.TextView; 
     import android.widget.Toast; 
     import com.google.android.gms.appindexing.Action; 
     import com.google.android.gms.appindexing.AppIndex; 
     import com.google.android.gms.appindexing.Thing; 
     import com.google.android.gms.common.api.GoogleApiClient; 
     import java.util.ArrayList; 
     import java.util.List; 

        public class MainActivity extends AppCompatActivity { 
        List<String> matchNumberArray = new ArrayList<String>(); 

       //String matchNumberArray[] = {}; 
       ArrayAdapter matchNumberAdapter = new ArrayAdapter<String>      (this, R.layout.previous_fragment, matchNumberArray); 

        List<String> teamNumberArray = new ArrayList<String>(); 


      // String teamNumberArray[] = {}; 
       ArrayAdapter teamNumberAdapter = new ArrayAdapter<String>(this, R.layout.previous_fragment, teamNumberArray); 

private SectionsPagerAdapter mSectionsPagerAdapter; 
private ViewPager mViewPager; 
/** 
* ATTENTION: This was auto-generated to implement the App Indexing API. 
* See https://g.co/AppIndexing/AndroidStudio for more information. 
*/ 
private GoogleApiClient client; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.container); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
    tabLayout.setupWithViewPager(mViewPager); 


    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, 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. @Override 

    // Handle item selection 
    switch (item.getItemId()) { 
     case R.id.saveMenuItem: 

      return true; 
     case R.id.ScreenShotMenuItem: 

      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 

} 

public void openScreenshotToast(MenuItem item) { 
    Toast toast = Toast.makeText(getApplicationContext(), "Screenshot button pressed", Toast.LENGTH_SHORT); 
    toast.show(); 
} 

public void saveMatchData (MenuItem item) { 
    //save button in my menu 
    //creates a toast to notify that it has been pressed 

    Toast toast = Toast.makeText(getApplicationContext(), "Save button pressed", Toast.LENGTH_SHORT); 
    toast.show(); 


    // create an EditText for matchNumberInput 
    EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput); 
    //assign value of matchNumberET(Edit Text) to match number 
    EditText matchNumber = (EditText) matchNumberET.getText(); 
    //attempted to assign to an int 
    int matchNumberValue = Integer.parseInt(matchNumber); 


    //same as abover just tried a different way that i read online 
    EditText teamNumberDT = (EditText) findViewById(R.id.teamNumberInput); 
    int teamNumber = Integer.parseInt(teamNumberDT.getText().toString()); 


    int i; 
    //i have an array for matchNumber values and teamNumber values 
    //they start empty and as of now still are 
    // 
    for (i = 0, i <= matchNumberArray.size(), i++);{ 
     if (matchNumberValue == matchNumberArray.get(i)){ 
      //code to add matchNumber if not already there 
     } 

     //both of these different ways to do this give me errors 

    } 
    if (teamNumberArray.get(i) == teamNumber) { 
     //code to add teamNumber if not already there 
    } 

} 

/** 
* ATTENTION: This was auto-generated to implement the App Indexing API. 
* See https://g.co/AppIndexing/AndroidStudio for more information. 
*/ 
public Action getIndexApiAction() { 
    Thing object = new Thing.Builder() 
      .setName("Main Page") // TODO: Define a title for the content shown. 
      // TODO: Make sure this auto-generated URL is correct. 
      .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) 
      .build(); 
    return new Action.Builder(Action.TYPE_VIEW) 
      .setObject(object) 
      .setActionStatus(Action.STATUS_TYPE_COMPLETED) 
      .build(); 
} 

@Override 
public void onStart() { 
    super.onStart(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client.connect(); 
    AppIndex.AppIndexApi.start(client, getIndexApiAction()); 
} 

@Override 
public void onStop() { 
    super.onStop(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    AppIndex.AppIndexApi.end(client, getIndexApiAction()); 
    client.disconnect(); 
} 


/** 
* A placeholder fragment containing a simple view. 
*/ 
public static class PlaceholderFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    private static final String ARG_SECTION_NUMBER = "section_number"; 

    public PlaceholderFragment() { 
    } 

    /** 
    * Returns a new instance of this fragment for the given section 
    * number. 
    */ 
    public static PlaceholderFragment newInstance(int sectionNumber) { 
     PlaceholderFragment fragment = new PlaceholderFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) { 
      View rootView = inflater.inflate(R.layout.fieldmap_fragment, container, false); 
      return rootView; 
     } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) { 
      View rootView = inflater.inflate(R.layout.datainput_fragment, container, false); 
      return rootView; 

     } else { 
      View rootView = inflater.inflate(R.layout.previous_fragment, container, false); 
      return rootView; 

     } 
    } 
} 

/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the sections/tabs/pages. 
*/ 
public class SectionsPagerAdapter extends FragmentPagerAdapter { 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a PlaceholderFragment (defined as a static inner class below). 
     return PlaceholderFragment.newInstance(position + 1); 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     switch (position) { 
      case 0: 
       return "FieldMap"; 
      case 1: 
       return "Match Data"; 
      case 2: 
       return "Previous"; 
     } 
     return null; 
    } 
} 

} `

+0

Integer.parseInt() принимает только строку. – Mordechai

ответ

1

Извлечение EditText значения как:

EditText matchNumberET = (EditText) findViewById(R.id.matchNumberInput);          
int matchNumberValue = Integer.parseInt(matchNumberET.getText().toString()); 

И, как видит код, я не мог найти свое Намерение в стороне App. Прочтите несколько руководств, как указано на Google's official site.

+0

Приложение предназначено для моей команды робототехники. Это собрать данные из наших сборников и использовать их, чтобы решить, кто является лучшей командой. –

+0

Рассмотрите вопрос о принятии ответа, если помогли ..! :) – W4R10CK

+0

Я сделал это для teamNumber. И затем сделал matchnumber разным, чтобы показать, что я пробовал разные способы. Нитье из них работает. –

0

Я сделал это для teamNumber. И затем сделал matchnumber разным, чтобы показать, что я пробовал разные способы. Нитье из них работает.

Смежные вопросы