0

im пытается подключиться к моему приложению, чтобы получить информацию из запроса базы данных, выполняется запись и переменные помещаются .but, когда он завершается с fn doinbackground, я нахожу переменную с переменной null, которая закрывается целая программа. я заметил, что когда в результате результат от блока try в doinbackgroundfn, он затем переходит к возврату в конце fn., а затем app stop. это код основного Bur Как выполняется запрос после и отпечатанного адаптера? основной код переменная возвращает null за пределами asynctask android. Исключение ненулевого указателя

import android.app.AlertDialog; 
 
import android.app.ProgressDialog; 
 
import android.content.Intent; 
 
import android.media.MediaPlayer; 
 
import android.os.AsyncTask; 
 
import android.os.Handler; 
 
import android.support.v7.app.AppCompatActivity; 
 
import android.os.Bundle; 
 
import android.util.Log; 
 
import android.view.View; 
 
import android.widget.AdapterView; 
 
import android.widget.ArrayAdapter; 
 
import android.widget.ListView; 
 

 
import org.json.JSONArray; 
 
import org.json.JSONException; 
 
import org.json.JSONObject; 
 

 
import java.io.BufferedReader; 
 
import java.io.BufferedWriter; 
 
import java.io.IOException; 
 
import java.io.InputStream; 
 
import java.io.InputStreamReader; 
 
import java.io.OutputStream; 
 
import java.io.OutputStreamWriter; 
 
import java.io.UnsupportedEncodingException; 
 
import java.net.HttpURLConnection; 
 
import java.net.MalformedURLException; 
 
import java.net.ProtocolException; 
 
import java.net.URL; 
 
import java.net.URLEncoder; 
 
import java.util.ArrayList; 
 

 
public class choose_buffet_items extends AppCompatActivity { 
 
    String []categouries; 
 
    ArrayList<buffetcategories> buff_list = new ArrayList<buffetcategories>(); 
 
    buffetcatadapter itemsAdapter; 
 

 
    ArrayAdapter adapter; 
 
    private static int SPLASH_TIME_OUT=2000; 
 
    AlertDialog alertDialog; 
 
    private boolean loggedIn = false; 
 
    String type; 
 
    String result; 
 
    @Override 
 
    protected void onCreate(Bundle savedInstanceState) { 
 
     super.onCreate(savedInstanceState); 
 
     setContentView(R.layout.activity_choose_buffet_items); 
 

 
     new JSONParse().execute(); 
 

 
      itemsAdapter = new buffetcatadapter(this, buff_list); 
 
      itemsAdapter.notifyDataSetChanged(); 
 

 
      ListView listView = (ListView) findViewById(R.id.listView_buffet); 
 
      listView.setAdapter(itemsAdapter); 
 

 
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
 
       @Override 
 
       public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
 
        String s =(String)adapter.getItem(i); 
 
        if(s.equals("Drinks")) 
 
        { 
 
         Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_drinks.class); 
 
         startActivity(numbersIntent); 
 
        } 
 
        else if(s.equals("Cakes")) 
 
        { 
 
         Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_cake.class); 
 
         startActivity(numbersIntent); 
 
        } 
 
        else if(s.equals("Appetizers")) 
 
        { 
 
         Intent numbersIntent = new Intent(choose_buffet_items.this,buffet_appetizers.class); 
 
         startActivity(numbersIntent); 
 
        } 
 
        else {Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_lunch.class); 
 
         startActivity(numbersIntent);} 
 

 
       } 
 
      }); 
 

 

 
      listView.setAdapter(adapter); 
 

 

 

 
    } 
 
    private class JSONParse extends AsyncTask<String, String, String> { 
 
     private ProgressDialog pDialog; 
 

 
     @Override 
 
     protected void onPreExecute() { 
 
      super.onPreExecute(); 
 
      alertDialog=new AlertDialog.Builder(choose_buffet_items.this).create(); 
 
      alertDialog.setTitle("Upadting Data"); 
 
      pDialog = new ProgressDialog(choose_buffet_items.this); 
 
      pDialog.setMessage("Getting Data ..."); 
 
      pDialog.setIndeterminate(false); 
 
      pDialog.setCancelable(true); 
 
      pDialog.show(); 
 

 

 
     } 
 

 

 
     @Override 
 
     protected String doInBackground(String... args) { 
 

 

 

 
       String login_URL = "http://2f179dfb.ngrok.io/getcat.php"; 
 
       try { 
 

 
        //Fetching the boolean value form sharedpreferences 
 

 

 
        URL url = new URL(login_URL); 
 
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
 
        httpURLConnection.setRequestMethod("POST"); 
 
        httpURLConnection.setDoOutput(true); 
 
        httpURLConnection.setDoInput(true); 
 

 
        InputStream inputStream = httpURLConnection.getInputStream(); 
 
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); 
 
        result = ""; 
 
        String line = ""; 
 
        while ((line = bufferedReader.readLine()) != null) { 
 
         result += line; 
 
        } 
 
        bufferedReader.close(); 
 
        inputStream.close(); 
 
        httpURLConnection.disconnect(); 
 
        Log.e("RESULT", result); 
 
        JSONObject jsonObject = new JSONObject(result); 
 

 
        JSONArray result1 = jsonObject.getJSONArray("result"); 
 
        //categouries=new String[result1.length()]; 
 
        for (int i = 0; i < result1.length(); i++) { 
 
         JSONObject c = result1.getJSONObject(i); 
 
         String category = c.getString("buffCategory"); 
 
         buff_list.add(new buffetcategories(category)); 
 

 

 
        } 
 

 
        return result; 
 

 

 
       } 
 
       catch (MalformedURLException e) { 
 
        e.printStackTrace(); 
 
       } catch (UnsupportedEncodingException e) { 
 
        e.printStackTrace(); 
 
       } catch (ProtocolException e) { 
 
        e.printStackTrace(); 
 
       } catch (IOException e) { 
 
        e.printStackTrace(); 
 
       } catch (JSONException e) { 
 
        e.printStackTrace(); 
 
       } 
 
       return result; 
 
      } 
 

 

 

 

 
     @Override 
 
     protected void onPostExecute(String r) { 
 
       itemsAdapter.notifyDataSetChanged(); 
 
       pDialog.dismiss(); 
 
      alertDialog.setMessage("hello"); 
 
      alertDialog.show(); 
 

 

 

 

 
     } 
 
    } 
 

 

 
}

это код адаптера

import android.app.Activity; 
 
import android.content.Context; 
 
import android.util.Log; 
 
import android.view.LayoutInflater; 
 
import android.view.View; 
 
import android.view.ViewGroup; 
 
import android.widget.ArrayAdapter; 
 
import android.widget.CheckBox; 
 
import android.widget.TextView; 
 

 
import java.util.ArrayList; 
 

 
/** 
 
* Created by extra on 25/12/2016. 
 
*/ 
 
public class buffetcatadapter extends ArrayAdapter<buffetcategories> { 
 
    Context context; 
 
    ArrayList<buffetcategories> items; 
 
    public buffetcatadapter(Activity context, ArrayList<buffetcategories> buffitems) { 
 
     // Here, we initialize the ArrayAdapter's internal storage for the context and the list. 
 
     // the second argument is used when the ArrayAdapter is populating a single TextView. 
 
     // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not 
 
     // going to use this second argument, so it can be any value. Here, we used 0. 
 
     super(context, 0,buffitems); 
 
     this.context=context; 
 
     this.items=buffitems; 
 
    } 
 

 

 
    @Override 
 
    public View getView(final int position, View convertView, ViewGroup parent) { 
 

 
     // Check if the existing view is being reused, otherwise inflate the view 
 
     View listItemView = convertView; 
 
     if (listItemView == null) { 
 
      listItemView = LayoutInflater.from(getContext()).inflate(
 
        R.layout.listviewbuffetcat, parent, false); 
 

 
     } 
 

 
     // Get the {@link AndroidFlavor} object located at this position in the list 
 
     final buffetcategories currentAndroidFlavor = getItem(position); 
 

 
     // Find the TextView in the list_item.xml layout with the ID version_name 
 
     TextView nameTextView = (TextView) listItemView.findViewById(R.id.categouries); 
 

 
     // Get the version name from the current AndroidFlavor object and 
 
     // set this text on the name TextView 
 
     nameTextView.setText(currentAndroidFlavor.getCategouries()); 
 
     Log.e("hhhh", nameTextView.getText().toString()); 
 

 
     // Find the TextView in the list_item.xml layout with the ID version_number 
 
     ; 
 
     // Return the whole list item layout (containing 2 TextViews and an ImageView) 
 
     // so that it can be shown in the ListView 
 
     return listItemView; 
 
    } 
 

 
    @Override 
 
    public int getCount() { 
 
     if(items == null) 
 
      return 0; 
 
     return items.size(); 
 
    } 
 

 
    @Override 
 
    public buffetcategories getItem(int i) { 
 
     return items.get(i); 
 
    } 
 
}

XML

<?xml version="1.0" encoding="utf-8"?> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    android:orientation="vertical" android:layout_width="match_parent" 
 
    android:layout_height="match_parent" 
 
    android:minHeight="@dimen/list_item_height" 
 
    android:padding="16dp" 
 
    android:background="#bbe0f7"> 
 
    <ListView 
 

 
     android:id="@+id/listView_buffet" 
 
     android:layout_width="match_parent" 
 
     android:layout_height="match_parent" > 
 

 
    </ListView> 
 

 
</LinearLayout>

XML

<?xml version="1.0" encoding="utf-8"?> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    android:orientation="vertical" android:layout_width="match_parent" 
 
    android:layout_height="match_parent" 
 
    android:minHeight="88dp"> 
 
    <TextView 
 
     android:id="@+id/categouries" 
 
     android:layout_height="wrap_content" 
 
     android:textAppearance="?android:textAppearanceMedium" 
 
     android:layout_width="wrap_content" 
 
     android:text="name" 
 

 

 
     /> 
 

 
</LinearLayout>

журнал кошки

com.rematchka.weddinghall E/AndroidRuntime: FATAL EXCEPTION: main 
 
                      Process: com.rematchka.weddinghall, PID: 27828 
 
                      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rematchka.weddinghall/com.rematchka.weddinghall.choose_buffet_items}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference 
 
                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 
 
                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
 
                       at android.app.ActivityThread.-wrap11(ActivityThread.java) 
 
                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
 
                       at android.os.Handler.dispatchMessage(Handler.java:102) 
 
                       at android.os.Looper.loop(Looper.java:148) 
 
                       at android.app.ActivityThread.main(ActivityThread.java:5417) 
 
                       at java.lang.reflect.Method.invoke(Native Method) 
 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
 
                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference 
 
                       at com.rematchka.weddinghall.choose_buffet_items.onCreate(choose_buffet_items.java:58) 
 
                       at android.app.Activity.performCreate(Activity.java:6237) 
 
                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
 
                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
 
                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  
 
                       at android.app.ActivityThread.-wrap11(ActivityThread.java)  
 
                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  
 
                       at android.os.Handler.dispatchMessage(Handler.java:102)  
 
                       at android.os.Looper.loop(Looper.java:148)  
 
                       at android.app.ActivityThread.main(ActivityThread.java:5417)  
 
                       at java.lang.reflect.Method.invoke(Native Method)  
 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  
 
12-25 02:33:15.908 27828-29079/com.rematchka.weddinghall E/RESULT: {"result":[{"buffCategory":"Drinks"},{"buffCategory":"Cakes"},{"buffCategory":"Appetizers"},{"buffCategory":"Lunch"}]}

ответ

0

reaso n вы получаете исключение NullPointerException, потому что к моменту звонка listView.setAdapter(adapter); вы не инициализировали adapter. Кроме того, String s =(String)adapter.getItem(i);, вероятно, даст вам аналогичное исключение. Вы имели в виду написать itemsAdapter?

+0

Да, я имел в виду адаптер предметов. Но я все равно получаю ту же ошибку –

+0

Он возвращает null в listview listview = (listview) findviewbyid (R.I'd. Listview_buffet) –

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

  • Нет связанных вопросов^_^