2014-01-07 5 views
-1

У меня загружен список «Загрузить список учеников»: но когда я нажимаю на какой-либо элемент из списка вместо перехода к следующему действию, он просто падает с помощью: NULL Pointer Execption: я связываю stID (студент Id) как дополнительные с намерением. Создание Toast onItemClick дает мне правильный идентификатор студента, как он может быть пустым, я думаю, что может быть какая-то проблема с контекстом, переданным в намерение; но это предположения; вы, ребята, помогаете мне указывать на ошибку;onitemclick null указатель исключение?

package com.example.connection; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.UUID; 




import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.ListView; 
import android.widget.Toast; 

import android.view.View; 
import android.view.View.OnClickListener; 

public class SelectStudent extends Activity { 
private BluetoothAdapter btAdapter = null; 
    private BluetoothSocket btSocket = null; 
    private OutputStream outStream = null; 

    // Well known SPP UUID 
    private static final UUID MY_UUID = 
     UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

    // Insert your server's MAC address 
    private static String address = "01:36:05:23:4A:44"; 
    public static String grpid; 
    Context obj; 
    Context objx; 
    /** Called when the activity is first created. */ 
    public void onCreate(Bundle savedInstanceState) { 
    objx=this; 
     super.onCreate(savedInstanceState); 
    setContentView(R.layout.select_student); 
    final ListView listview = (ListView) findViewById(R.id.stdlist); 
    final ArrayList<String> list = new ArrayList<String>(); 
    Button btnLogin= (Button) findViewById(R.id.LoadList); 
    Button btnClose =(Button) findViewById(R.id.Exit); 
    btnClose.setText("Close"); 

    Button insert = (Button) findViewById(R.id.add_btn); 




insert.setOnClickListener(new OnClickListener() { 

      public void onClick(View arg0) { 

       Intent intent = new Intent(SelectStudent.this, InsertMarks.class); 
       startActivity(intent); 

      } 
     }); 

     btAdapter = BluetoothAdapter.getDefaultAdapter(); 
     btnClose.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
      System.exit(0); 
      } 
     }); 
     btnLogin.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
      try 
      { 
       // Set up a pointer to the remote node (Machine/PC) using it's address. 
       BluetoothDevice device = btAdapter.getRemoteDevice(address); 

       // -- Notes -- // 
       // Two things are needed to make a connection: 
       // A MAC address, which we got above. 
       // A Service ID or UUID. 

      // UUID for SPP. 
       try { 
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); 
       } catch (IOException e) { 
        //AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); 
       } 

       // During message pass no devise discovery is allowed. 
       btAdapter.cancelDiscovery(); 

       // Establish the connection. This will block until it connects. 
       try { 
        btSocket.connect(); 
        //out.append("\n...Connection established and data link opened..."); 
       } catch (IOException e) { 
        try { 
        btSocket.close(); 
        } catch (IOException e2) { 
        //AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); 
        } 
       } 

       // Create a data stream so we can talk to server. 
       //out.append("\n...Sending message to server..."); 
       String message = "2\n"; 
       //out.append("\n\n...The message that we will send to the server is: "+message); 

       try { 
        outStream = btSocket.getOutputStream(); 
       } catch (IOException e) { 
        //AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + "."); 
       } 

       byte[] msgBuffer = message.getBytes(); 
       try { 
        outStream.write(msgBuffer); 
       } catch (IOException e) { 
        String msg = "In onResume() and an exception occurred during write: " + e.getMessage(); 
        if (address.equals("00:00:00:00:00:00")) 
        msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code"; 
        msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n"; 

        //AlertBox("Fatal Error", msg);  
       } 
       InputStream inStream; 
       try { 
        inStream = btSocket.getInputStream(); 
        BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream)); 
        String lineRead=bReader.readLine(); 
        Toast.makeText(objx, lineRead, Toast.LENGTH_SHORT).show(); 
          bReader.close(); 
          inStream.close(); 
          do 
          { 
           try 
           { 
            String id,temp; 
            int length; 
            id=lineRead.substring(0, lineRead.indexOf("*")); 
            length=lineRead.indexOf("*"); 
            temp=lineRead.substring(length+1); 
            lineRead=temp; 
            if(!id.equals("")) 
             list.add(id); 

           } 
           catch(Exception exp) 
           { 
            Toast.makeText(getApplication(), exp.getMessage(), Toast.LENGTH_SHORT).show(); 
           } 
           final StableArrayAdapter adapter = new StableArrayAdapter(objx, 
             android.R.layout.simple_list_item_1, list); 
            listview.setAdapter(adapter); 
          } 
          while(lineRead.contains("*")); 
          //finish(); 

       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

       //out.append("\n...In onPause()..."); 



       if (outStream != null) { 
        try { 
        outStream.flush(); 
        } catch (IOException e) { 
        // AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + "."); 
        } 
       } 

       try  { 
        btSocket.close(); 
       } catch (IOException e2) { 
       // AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); 
       } 

       //bReader.close(); 
       //inStream.close(); 

      } 
      catch(Exception exp) 
      { 
       Toast.makeText(getApplication(), "Error Found!"+exp.getMessage(), Toast.LENGTH_SHORT).show(); 
      } 

      } 

     }); 





     listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 


      @Override 
       public void onItemClick(AdapterView<?> parent, final View view, 
        int position, long id) { 
       try 
       { 
        final String item = (String) parent.getItemAtPosition(position); 

        //InsertMarks.stdid=position; 

        Intent i= new Intent(SelectStudent.this,InsertMarks.class); 
        i.putExtra("stID", item); 
        startActivity(i); 
        //Toast.makeText(getApplication(), "Working"+item, Toast.LENGTH_SHORT).show(); 

        //String app = SelectStudent.this.toString(); 

        //Toast.makeText(getApplication(), "Current Context: "+app, Toast.LENGTH_LONG).show(); 

        //next(); 
       } 
       catch(Exception exp) 
       { 
        //Toast.makeText(objx, exp.getMessage(), Toast.LENGTH_LONG).show(); 
       } 
       }; 


      }); 
      } 

      private class StableArrayAdapter extends ArrayAdapter<String> { 

      HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); 

      public StableArrayAdapter(Context context, int textViewResourceId, 
       List<String> objects) { 
       super(context, textViewResourceId, objects); 
       for (int i = 0; i < objects.size(); ++i) { 
       mIdMap.put(objects.get(i), i); 
       } 
      } 

      @Override 
      public long getItemId(int position) { 
       String item = getItem(position); 
       return mIdMap.get(item); 
      } 

      @Override 
      public boolean hasStableIds() { 
       return true; 
      } 

      } 
     } 

МОЯ XML Layout:

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginLeft="20dp" 
     android:layout_marginTop="15dp" 
     android:text="@string/SelectStudent" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <ListView 
     android:id="@+id/stdlist" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/Exit" 
     android:layout_alignLeft="@+id/textView1" 
     android:layout_alignRight="@+id/Exit" 
     android:layout_below="@+id/textView1" 
     android:layout_marginTop="16dp" 
     android:scrollbarAlwaysDrawVerticalTrack="true" > 

    </ListView> 

    <Button 
     android:id="@+id/LoadList" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/Exit" 
     android:layout_alignBottom="@+id/Exit" 
     android:layout_alignParentLeft="true" 
     android:text="@string/LoadList" /> 

    <Button 
     android:id="@+id/Exit" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_marginBottom="17dp" 
     android:layout_toRightOf="@+id/LoadList" 
     android:text="@string/Next" /> 

    <Button 
     android:id="@+id/add_btn" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/stdlist" 
     android:layout_toRightOf="@+id/stdlist" 
     android:text="@string/add" /> 

     </RelativeLayout> 

Мне нужна способ, чтобы перейти к следующей операции с студенческим билетом передается как дополнительная:

 01-07 19:28:28.888: E/AndroidRuntime(4354): FATAL EXCEPTION: main 
     01-07 19:28:28.888: E/AndroidRuntime(4354): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.connection/com.example.connection.InsertMarks}: java.lang.NullPointerException 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2084) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2111) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.ActivityThread.access$600(ActivityThread.java:134) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1251) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.os.Handler.dispatchMessage(Handler.java:99) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.os.Looper.loop(Looper.java:137) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.ActivityThread.main(ActivityThread.java:4666) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at java.lang.reflect.Method.invokeNative(Native Method) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at java.lang.reflect.Method.invoke(Method.java:511) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at dalvik.system.NativeStart.main(Native Method) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): Caused by: java.lang.NullPointerException 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at com.example.connection.InsertMarks.onCreate(InsertMarks.java:48) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.Activity.performCreate(Activity.java:4510) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2048) 
     01-07 19:28:28.888: E/AndroidRuntime(4354): ... 11 more 
+2

Что такое строка 48 на 'InsertMarks'' Activity'? – Emmanuel

+1

, пожалуйста, избавитесь от этого System.exit (0) – Blackbelt

+0

«NullPointerException» в действии InsertMarks ... проверьте его по строке 48 – MikeKeepsOnShine

ответ

0

Глядя на вас LogCat, который говорит, что есть a NullPointerException в InsertMarks деятельности, я думаю, что вы не взыскаете значение, которое вы передаете от SelectStudent до InsertMarks.

Вы должны сделать так (в InsertMarks):

String yourStudent = getIntent().getStringExtra("stID"); 

Но я не могу быть уверен, потому что вы не отправлял InsertMarks код.

+1

Спасибо MikeKeepsOnShine: Keep Shining – user3164310

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