从在线数据库填充listview时出现奇怪的空指针异常

时间:2014-10-28 07:25:15

标签: java android listview nullpointerexception

我正在开发一个新闻Android应用程序,我有以下代码用来自在线服务器的文本和图像填充列表视图:

package info.androidhive.actionbar;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class News extends ListActivity implements
ActionBar.OnNavigationListener  {

    private ProgressDialog pd;
    Handler handler;
    ArrayList<NameValuePair> nameValuePairs;
    HttpResponse response;
    HttpEntity entity;
    HttpClient httpclient;
    String wholepost="";
//  CustomAdapter adapter;
    HttpPost httppost;
    TextView scrolltext;
    //String date,content,sender1,sender2,mid,nc;
     CategoryAdapter adapter;
    String type,username,title,nc,content,date,time,internet="yes";
     private ListView listView1;
    private String titlearray[];
    private String contentarray[];
    private String datearray[];
    private String task_type[];
    private String deleted_task[];
    private String task_id[];
    String[] postsinarray;
    String[] arrayinlist;
    JSONArray arr;
    Bitmap[] bit=null;
    //String type;

    private ActionBar actionBar;


    // Refresh menu item
    private MenuItem refreshMenuItem;


  ArrayList<HashMap<String, Object>> searchResults;


  ArrayList<HashMap<String, Object>> originalValues;
  LayoutInflater inflater;

  @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
  public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 setContentView(R.layout.activity_main);
// final ListView playerListView=(ListView) findViewById(android.R.id.list);


    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

    forceRTLIfSupported();

    actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle("أخبار الساعة");  


scrolltext=(TextView) findViewById(R.id.textView1);
scrolltext.setText("");
scrolltext.setTextColor(Color.BLACK);



pd=new ProgressDialog(News.this,R.style.TransparentProgressDialog);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("جار تحميل الأخبار");
pd.setCancelable(false);
pd.setIndeterminate(true);
handler=new Handler();



inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

///////////////////////////////////////////////////////////////////////

ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) 

{

//  new ProgressTask().execute();

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
    pd.show();
    Thread thread = new Thread() {

        public void run () {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);


            //httpclient = new DefaultHttpClient();
            httpclient = new DefaultHttpClient();
            String type2="moonwalker";
            httppost = new HttpPost("http://www.mypage.com/myfolder/mypage.php?Username="+type2+"");
            try
            {
            nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("Type",type));
            nameValuePairs.add(new BasicNameValuePair("Date",date));
            nameValuePairs.add(new BasicNameValuePair("Title",title));
            nameValuePairs.add(new BasicNameValuePair("Content",content));
            nameValuePairs.add(new BasicNameValuePair("Time",time));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
            response = httpclient.execute(httppost);



            if(response.getStatusLine().getStatusCode()==200)
            {

            entity=response.getEntity();
            if(entity !=null)
            {
                InputStream instream=entity.getContent();
            try {
            JSONArray jArray = new JSONArray(convertStreamToString(instream));
arr=jArray;
        //  int jArrayLength = arr.length();
            postsinarray = new String[arr.length()];
            arrayinlist=new String[arr.length()];

            //final List<String> listContents = new ArrayList<String>(jArrayLength);
            //thelist=listContents;


             Category task_data[] = new Category[arr.length()];   

              titlearray=new String[arr.length()];
             contentarray=new String[arr.length()];
             datearray=new String[arr.length()];
            task_type=new String[arr.length()];
            task_id=new String[arr.length()];
            deleted_task=new String[arr.length()];

        for(int i =0; i<arr.length(); i++){
try
{
            JSONObject json_data = arr.getJSONObject(i);


     //      String postcontent=new String(json_data.getString("Content").getBytes("ISO-8859-1"), "UTF-8");

      //    String TAG_ID = null;
        String postcontent=URLDecoder.decode(json_data.getString("Content"), "UTF-8");
        wholepost= wholepost+postcontent+"\t\t\t\t";

         contentarray[i]=postcontent;

         if(postcontent.length()>64)
         {
             String subpost=postcontent.substring(0,50);
             String newcontent=subpost+"...";
             nc=newcontent;

         }
         else
         {
             nc=postcontent;
         }



         String posttype=json_data.getString("Type");

         task_type[i]=posttype;
        StrictMode.ThreadPolicy policy1= new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

        URL newurl = new URL("http://mypage.com/myfolder/photos/mini_"+posttype+".jpg"); 
        Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());


         task_data[i]=new Category(mIcon_val, json_data.getString("Title"),nc,json_data.getString("Date"),json_data.getString("Taskid"));
         titlearray[i]=json_data.getString("Title");
         datearray[i]=json_data.getString("Date");

         task_id[i]=json_data.getString("Taskid");




adapter = new CategoryAdapter(News.this, R.layout.list_row, task_data);






//listcount=listView1.getCount();

}catch(Exception ex){Toast.makeText(getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();}
        }



           pd.dismiss();


            }catch(JSONException e){

            }}}
            }//End of first try

            catch(Exception e)
            {
            // Toast.makeText(getBaseContext(),"CONNECTION ERROR",Toast.LENGTH_LONG).show();

            }
            handler.post(new Runnable() {
                @Override
                public void run() {

                    listView1 = (ListView)findViewById(android.R.id.list);

                    listView1.setAdapter(adapter);


                     adapter.notifyDataSetChanged();

                     SpannableString ss = new SpannableString("\t\t\t\t"+wholepost); 
                     Drawable d = getResources().getDrawable(R.drawable.mini_globe); 
                     d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 
                     ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); 
                     ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                     scrolltext.setText(ss);

                    pd.dismiss();

                }
            });

        }

    };

    thread.start(); 
/////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 // End of first catch
}
else
{
    Toast.makeText(getBaseContext(),"No internet connection", Toast.LENGTH_LONG).show();    
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




listView1 = (ListView)findViewById(android.R.id.list);
listView1.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

        ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) 
        {
            String postcontent=contentarray[arg2];
            String posttitle=titlearray[arg2];
            String postphoto=task_type[arg2];



             Intent intent = new Intent(News.this, Postcontent.class);

                // 2. put key/value data
                intent.putExtra("message", "Hello From MainActivity");

                // 3. or you can add data to a bundle
                Bundle extras = new Bundle();
                extras.putString("title",posttitle);
                extras.putString("content",postcontent);
                extras.putString("photo",postphoto);

                // 4. add bundle to intent
                intent.putExtras(extras);

                // 5. start the activity
                startActivity(intent);
        }
        else
        {
            Toast.makeText(getBaseContext(),"No internet connection", Toast.LENGTH_LONG).show();
        }





    }



});




 }


 //define your custom adapter



 private static String convertStreamToString(InputStream is)
 {


BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{

while ((line = reader.readLine()) != null) {
   sb.append(line + "\n");
}
}catch(IOException e)
{

}
finally
{
    try{
        is.close();
    }catch(IOException e)
    {

    }
    }return sb.toString();



 }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main_actions, menu);



        return super.onCreateOptionsMenu(menu);
    }

    /**
     * On selecting action bar icons
     * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {

        case R.id.action_refresh:
            // refresh
            refreshMenuItem = item;

            new ProgressTask().execute();
            return true;

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

    /**
     * Launching new activity
     * */


    /*
     * Actionbar navigation item select listener
     */
    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        // Action to be taken after selecting a spinner item
        return false;
    }





    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void forceRTLIfSupported()
    {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        }
    }


    protected void onPostExecute(Object  result) {
        try {
            if ((this.pd != null) && this.pd.isShowing()) {
                this.pd.dismiss();
            }
        } catch (final IllegalArgumentException e) {
            // Handle or log or ignore
        } catch (final Exception e) {
            // Handle or log or ignore
        } finally {
            this.pd = null;
        }  
    }


    private class ProgressTask extends AsyncTask <Void,Void,Void>
    {

        @Override
        protected void onPreExecute()
        {
            refreshMenuItem.setActionView(R.layout.action_progressbar);
            refreshMenuItem.expandActionView();

        }

        @Override
        protected Void doInBackground(Void... params) 
        {

            ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) 
            {
                internet="yes";
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);


            //httpclient = new DefaultHttpClient();
            httpclient = new DefaultHttpClient();
            String type2="moonwalker";
            httppost = new HttpPost("http://mypage.com/myfolder/mypage.php?Username="+type2+"");
        try
            {
            nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("Type",type));
            nameValuePairs.add(new BasicNameValuePair("Date",date));
            nameValuePairs.add(new BasicNameValuePair("Title",title));
            nameValuePairs.add(new BasicNameValuePair("Content",content));
            nameValuePairs.add(new BasicNameValuePair("Time",time));
//
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
            response = httpclient.execute(httppost);
//
//
//
            if(response.getStatusLine().getStatusCode()==200)
            {
//
            entity=response.getEntity();
            if(entity !=null)
            {
                InputStream instream=entity.getContent();
            try {
            JSONArray jArray = new JSONArray(convertStreamToString(instream));
arr=jArray;
        //  int jArrayLength = arr.length();
            postsinarray = new String[arr.length()];
            arrayinlist=new String[arr.length()];



            }catch(JSONException e){
//
            }}}
        }//End of first try
//
            catch(Exception e)
            {

            }

//                  
                     Category task_data[] = new Category[arr.length()];   

                      titlearray=new String[arr.length()];
                     contentarray=new String[arr.length()];
                     datearray=new String[arr.length()];
                    task_type=new String[arr.length()];
                    task_id=new String[arr.length()];
                    deleted_task=new String[arr.length()];
//                  
                    for(int i =0; i<arr.length(); i++){
try
{
                    JSONObject json_data = arr.getJSONObject(i);



                String postcontent=URLDecoder.decode(json_data.getString("Content"), "UTF-8");
                wholepost= wholepost+postcontent+"\t\t\t\t";

                 contentarray[i]=postcontent;
//                   
                 if(postcontent.length()>64)
                 {
                     String subpost=postcontent.substring(0,50);
                     String newcontent=subpost+"...";
                     nc=newcontent;

                 }
                 else
                 {
                     nc=postcontent;
                 }

                 String posttype=json_data.getString("Type");

                 task_type[i]=posttype;
                StrictMode.ThreadPolicy policy2 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
//                  
                URL newurl = new URL("http://mypage.com/myfolder/photos/mini_"+posttype+".jpg"); 
                Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());

                 task_data[i]=new Category(mIcon_val, json_data.getString("Title"),nc,json_data.getString("Date"),json_data.getString("Taskid"));
                 titlearray[i]=json_data.getString("Title");
                 datearray[i]=json_data.getString("Date");

                 task_id[i]=json_data.getString("Taskid");




    adapter = new CategoryAdapter(News.this, R.layout.list_row, task_data);

//
}
        catch(Exception ex)
        {
            Toast.makeText(getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
            }
                }
        }
        else
        {internet="non";
            //Toast.makeText(getBaseContext(),"No internet connection", Toast.LENGTH_LONG).show();
        }
        return null;
        }

        @Override
        protected void onPostExecute(Void result) 
        {
            if(internet.equals("yes"))
            {
                listView1 = (ListView)findViewById(android.R.id.list);

                listView1.setAdapter(adapter);


                 adapter.notifyDataSetChanged();
            }
            else
            {
                Toast.makeText(getBaseContext(),"No internet connection", Toast.LENGTH_LONG).show();
            }



//           scrolltext.setText(wholepost);

            refreshMenuItem.collapseActionView();
            // remove the progress bar view
            refreshMenuItem.setActionView(null);
            //Toast.makeText(getBaseContext(),message, Toast.LENGTH_LONG).show();

        }

    }

}

如果我第一次打开应用程序,它会崩溃并给我以下错误:

10-28 09:09:28.680: E/AndroidRuntime(2840): FATAL EXCEPTION: main
10-28 09:09:28.680: E/AndroidRuntime(2840): java.lang.NullPointerException
10-28 09:09:28.680: E/AndroidRuntime(2840):     at info.androidhive.actionbar.News$1$1.run(News.java:283)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at android.os.Handler.handleCallback(Handler.java:725)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at android.os.Looper.loop(Looper.java:137)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at android.app.ActivityThread.main(ActivityThread.java:5041)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at java.lang.reflect.Method.invokeNative(Native Method)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at java.lang.reflect.Method.invoke(Method.java:511)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-28 09:09:28.680: E/AndroidRuntime(2840):     at dalvik.system.NativeStart.main(Native Method)

当我在崩溃后立即打开它时,它可以正常工作,如果我等待大约20分钟并尝试再次打开它会崩溃,同样的过程重复,任何人都知道发生了什么?

1 个答案:

答案 0 :(得分:0)

你的变量&#34;适配器&#34;抛出nullpointerexception ...尝试处理execption ...这可能是由于&#34; adapter&#34;的初始化声明没有执行...因为您已将该代码放入

if(response.getStatusLine().getStatusCode()==200)

......我认为这个条件没有运行..