2014-06-22 26 views
0

我是新來的android,我試圖把我的mysql服務器的信息放到android的listview中。列表項中有文字和圖片。如果我嘗試僅添加文本,它將起作用。錯誤:從mysql錯誤填充Android列表錯誤

06-22 22:54:43.215: E/AndroidRuntime(32644): FATAL EXCEPTION: main 
06-22 22:54:43.215: E/AndroidRuntime(32644): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rolab37.lostpet/com.rolab37.lostpet.DashboardActivity}: java.lang.NullPointerException 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.ActivityThread.access$700(ActivityThread.java:159) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.os.Handler.dispatchMessage(Handler.java:99) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.os.Looper.loop(Looper.java:176) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.ActivityThread.main(ActivityThread.java:5419) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at java.lang.reflect.Method.invokeNative(Native Method) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at java.lang.reflect.Method.invoke(Method.java:525) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at dalvik.system.NativeStart.main(Native Method) 
06-22 22:54:43.215: E/AndroidRuntime(32644): Caused by: java.lang.NullPointerException 
06-22 22:54:43.215: E/AndroidRuntime(32644): at com.rolab37.lostpet.DashboardActivity.connect(DashboardActivity.java:201) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at com.rolab37.lostpet.DashboardActivity.onCreate(DashboardActivity.java:67) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.Activity.performCreate(Activity.java:5372) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
06-22 22:54:43.215: E/AndroidRuntime(32644): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257) 
06-22 22:54:43.215: E/AndroidRuntime(32644): ... 11 more 

因此,這裏是我的代碼: DashboardActivity.java

package com.example.dashboard; 

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.lang.ref.WeakReference; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Vector; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.net.http.AndroidHttpClient; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.webkit.URLUtil; 
import android.widget.ArrayAdapter; 
import android.widget.BaseAdapter; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.TextView; 

import com.rolab37.lostpet.library.UserFunctions; 

public class DashboardActivity extends Activity { 
    UserFunctions userFunctions; 
    Button btnLogout; 
    TextView text; 
    ListView listView; 
    private StockAdaptor stockAdaptor; 

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

     /** 
     * Dashboard Screen for the application 
     * */   
     // Check login status in database 
     userFunctions = new UserFunctions(); 
     if(userFunctions.isUserLoggedIn(getApplicationContext())){ 
      setContentView(R.layout.dashboard); 

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 

      connect(); 


      btnLogout = (Button) findViewById(R.id.btnLogout); 

      btnLogout.setOnClickListener(new View.OnClickListener() { 

       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        userFunctions.logoutUser(getApplicationContext()); 
        Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
        login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(login); 
        // Closing dashboard screen 
        finish(); 
       } 
      }); 

     }else{ 
      // user is not logged in show login screen 
      Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
      login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(login); 
      // Closing dashboard screen 
      finish(); 
     } 
    } 

    private class StockAdaptor extends BaseAdapter { //The stocks list adaptor 

     class ViewHolder { 
      TextView name; 
      TextView price; 
      ImageView image; 
     } 

     private LayoutInflater layoutInflater; 
     private StockInformation[] stocks = null; //Array of stocks 
     private ListView stocksListView = null; 

     public StockAdaptor(Context context) { 
      super(); 
      layoutInflater = LayoutInflater.from(context); 
     } 

     public void setStockList(StockInformation[] stocksinfo) { 
      this.stocks = stocksinfo;// //////////////LITERALLY THIS 

     } 

     @Override 
     public int getCount() { 
      return stocks.length; 
     } 

     @Override 
     public Object getItem(int position) { 
      return stocks[position]; 
     } 

     public StockInformation[] getAll() { //Return the array of stocks 
      return stocks; 
     } 

     @Override 
     public long getItemId(int position) { 
      return 0; 
     } 

     public View getView(int position, View convertView, ViewGroup parent) { 
      ViewHolder holder; //New holder 
      if (convertView == null) { 
       convertView = layoutInflater.inflate(R.layout.dashboard, 
         null); 
       holder = new ViewHolder(); 
       // Creates the new viewholder define above, storing references to the children 
       holder.name = (TextView) convertView.findViewById(R.id.name); 
       holder.price = (TextView) convertView.findViewById(R.id.location); 
       holder.image = (ImageView) convertView.findViewById(R.id.image); 

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

       if (holder.image != null) { 
        if (holder.image.getDrawable() == null) { 
         new ImageDownloaderTask(holder.image, null)         .execute(stocks[position].imageurl); //Download the image using the imageurl 

        } 
       } 
       convertView.setTag(holder); 
      } else { 
       stocksListView = (ListView) findViewById(android.R.id.list); 
       holder = (ViewHolder) convertView.getTag(); 
      } 

      holder.name.setText(stocks[position].name); 
      holder.price.setText(stocks[position].location); 

      return convertView; 
     } 
    } 

    private void connect() { 
     String data; 
     List<String> r = new ArrayList<String>(); 
     ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r); 
     ListView list=(ListView)findViewById(R.id.list); 
      try { 
       DefaultHttpClient client = new DefaultHttpClient(); 
       HttpGet request = new HttpGet("http://localhost/list.php"); 
       HttpResponse response = client.execute(request); 
       HttpEntity entity=response.getEntity(); 
       data=EntityUtils.toString(entity); 
       Log.e("STRING", data); 
       try { 
       JSONArray json=new JSONArray(data); 

       Vector<StockInformation> vstocks = new Vector<StockInformation>(); 
       Log.e("debug", "aici"); 
       for (int i = 0; i < json.length(); i++) { 
        JSONObject obj=json.getJSONObject(i); 
        StockInformation stock = new StockInformation(); 
        stock.name = obj.optString("name"); 
        stock.location = obj.optString("location"); 
        stock.imageurl = obj.getString("imageurl"); 
        Log.e("StockLog", stock.name + stock.location + stock.imageurl); 
        vstocks.add(stock); 
       } 
       StockInformation[] stocks = new StockInformation[json.length()]; 

       int stockscount = json.length(); 
       for (int n = 0; n < stockscount; n++) 
       {    
        stocks[n] = vstocks.get(n); 
       } 
       stockAdaptor.setStockList(stocks); 
       list.setAdapter(stockAdaptor); 
       /* 

       for(int i=0;i<json.length(); i++) { 
         JSONObject obj=json.getJSONObject(i); 
         String name=obj.getString("name"); 
         String year=obj.getString("year"); 
         String age=obj.getString("age"); 
         Log.e("STRING", name); 
         r.add(name); 
         r.add(year); 
         r.add(age); 
         list.setAdapter(adapter); 
       }*/ 

       } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } 

      } catch (ClientProtocolException e) { 
       Log.d("DashboardActivity", e.getLocalizedMessage()); 
      } catch (IOException e) { 
       Log.d("DashboardActivity", e.getLocalizedMessage()); 
      } 
    } 

    private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> { 
     private final WeakReference<ImageView> imageViewReference; 

     public ImageDownloaderTask(ImageView imageView, View view) { 
      imageViewReference = new WeakReference<ImageView>(imageView); 
     } 

     @Override 
     // Actual download method, run in the task thread 
     protected Bitmap doInBackground(String... params) { 
      // params comes from the execute() call: params[0] is the url. 
      return downloadBitmap(params[0]); 
     } 

     @Override 
     // Once the image is downloaded, associates it to the imageView 
     protected void onPostExecute(Bitmap bitmap) { 
      if (isCancelled()) { 
       bitmap = null; 
      } 

      if (imageViewReference != null) { 
       ImageView imageView = imageViewReference.get(); 
       if (imageView != null) { 

        if (bitmap != null) { 
         imageView.setImageBitmap(bitmap); 
        } else { 
         // 
        } 
       } 

      } 

     } 

     Bitmap downloadBitmap(String url) { 
      if(URLUtil.isValidUrl(url)){ 

       final AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); 
       final HttpGet getRequest = new HttpGet(url); 
       try { 
        HttpResponse response = client.execute(getRequest); 
        final int statusCode = response.getStatusLine().getStatusCode(); 
        if (statusCode != HttpStatus.SC_OK) { 
         Log.w("ImageDownloader", "Error " + statusCode 
           + " while retrieving bitmap from " + url); 
         return null; 
        } 

        final HttpEntity entity = response.getEntity(); 
        if (entity != null) { 
         InputStream inputStream = null; 
         try { 
          inputStream = entity.getContent(); 
          try { 
           byte[] buffer = new byte[8192]; 
           int bytesRead; 
           ByteArrayOutputStream output = new ByteArrayOutputStream(); 
           while ((bytesRead = inputStream.read(buffer)) != -1) { 
            output.write(buffer, 0, bytesRead); 
           } 
           return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length); 
          } catch (IllegalArgumentException e) { 
           e.printStackTrace(); 
           Log.i("IAE", "in stocks"); 
           return null; 
          } 
         } finally { 
          if (inputStream != null) { 
           inputStream.close(); 
          } 
          entity.consumeContent(); 
         } 
        } 
       } catch (Exception e) { 
        getRequest.abort(); 
        Log.w("ImageDownloader", "Error while retrieving bitmap from " + url); 
       } finally { 
        if (client != null) { 
         client.close(); 
        } 
       } 
       return null; 

      } 
      return null; 
     } 

    } 
} 

StockInformation.java 包com.example.dashboard;

public class StockInformation { 

    public String name; 
    public String location; 
    public String imageurl; 

} 

dashboard.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="#3b3b3b"> 

    <TextView android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="WELCOME" 
       android:textSize="40dip" 
       android:gravity="center" 
       android:layout_marginTop="20dip"/> 

     <ListView 
      android:id="@+id/list" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true" > 
     </ListView> 

    <Button android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Logout Me" 
     android:textSize="20dip" 
     android:textColor="#21dbd4" 
     android:textStyle="bold" 
     android:id="@+id/btnLogout" 
     android:layout_marginTop="80dip" 
     android:background="@null"/> 

</LinearLayout> 

和dashboardlist.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:minHeight="50dp" 
    android:orientation="vertical" > 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <ImageView 
      android:id="@+id/image" 
      android:layout_width="70dp" 
      android:layout_height="70dp" /> 

     <TextView 
      android:id="@+id/name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:lineSpacingExtra="3dp" 
      android:paddingLeft="5dp" 
      android:paddingTop="5dp" 
      android:text="" /> 

     <TextView 
      android:id="@+id/location" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:paddingLeft="5dp" 
      android:paddingTop="5dp" 
      android:text="" /> 
    </LinearLayout> 

</LinearLayout> 

這是JSON

[{"name":"Nicu","location":"1983","imageurl":"http:\/\/www.fancyicons.com\/free-icons\/103\/flags\/png\/256\/romania_flag_256.png"},{"name":"Adina","location":"1987","imageurl":"http:\/\/icons.iconarchive.com\/icons\/custom-icon-design\/flag-3\/256\/United-Kingdom-flag-icon.png"}] 

希望你能幫助

回答

0

這是因爲201行的DashboardActivity中的stockAdaptor爲空。

+0

好的,接下來我該怎麼做。 「stocks」看起來像是有值 – user3765406

+0

您應該在DashboardActivity的onCreate方法中爲stockAdapter變量賦值,如:stockAdapter = new StockAdaptor(this); –