簡體   English   中英

無法在我的Android應用程序中將數據從mysql數據庫獲取到ListView

[英]Unable to fetch data from mysql database to ListView in my Android Application

我的應用程序是這樣工作的。 首先, MainActivity.java顯示從mysql數據庫獲取的電影列表。 在列表中單擊電影時, SongsActivity.java將打開並顯示該特定電影中的歌曲列表。 第一個活動工作正常,但是當我單擊電影時,第二個活動打開為空白! 尚未完成抓取! 以下是我的代碼,請幫助我。

MainActivity.java

package com.example.telugump3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity{

    Activity context;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    ProgressDialog pd;
    CustomAdapter adapter;
    ListView listProduct;
    ArrayList<String> records;

    protected void onCreate(Bundle savedInstanceState) {

        //TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context=this;
        records=new ArrayList<String>();
        listProduct=(ListView)findViewById(R.id.product_list);
        adapter=new CustomAdapter(context, R.layout.list_item,R.id.pro_name, records);
        listProduct.setAdapter(adapter);
        listProduct.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id){

                String sText = ((TextView) v.findViewById(R.id.pro_name)).getText().toString();
                Intent songIntent = new Intent(getApplicationContext(), SongActivity.class);
                songIntent.putExtra("movie_name", sText );
                startActivity(songIntent);
            }          
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        //create a LayoutTransition object       
        return true;
    }

    public void onStart(){

        super.onStart(); 
        //execute background task
        BackTask bt=new BackTask();
        bt.execute();
    }

    //background process to make a request to server and list product information
    private class BackTask extends AsyncTask<Void,Void,Void>{  

        protected void onPreExecute(){

            super.onPreExecute();
            pd = new ProgressDialog(context);
            pd.setTitle("Retrieving data");
            pd.setMessage("Please wait.");
            pd.setCancelable(true);
            pd.setIndeterminate(true);
            pd.show();       
        }

        protected Void doInBackground(Void...params){ 

            InputStream is=null;
            String result="";
            try{

                httpclient=new DefaultHttpClient();
                httppost= new HttpPost("http://necrecords.16mb.com/getproducts.php");
                response=httpclient.execute(httppost);         
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }catch(Exception e){

                if(pd!=null)
                pd.dismiss();  //close the dialog if error occurs 
                Log.e("ERROR",e.getMessage());
            }

            //convert response to string
            try{

                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {

                    sb.append(line + "\n");
                }
                is.close();         
                result=sb.toString();
            }catch(Exception e){

                Log.e("ERROR", "Error converting result "+e.toString());
            }

            //parse json data
            try{

                JSONArray jArray =new JSONArray(result);
                for(int i=0;i<jArray.length();i++){

                    JSONObject json_data = jArray.getJSONObject(i);
                    String record = json_data.getString("pname")+"__"+json_data.getInt("uprice");
                    records.add(record);
                }              
            }
            catch(Exception e){

                Log.e("ERROR", "Error pasting data "+e.toString());
            }
            return null;
        }              

        protected void onPostExecute(Void result){

            if(pd!=null) pd.dismiss(); //close dialog
            adapter.notifyDataSetChanged(); //notify the ListView to get new records
        }           
    }
} 

SongsActivity.java

package com.example.telugump3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class SongActivity extends Activity{

    Activity context;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    ProgressDialog pd;
    CustomAdapter adapter;
    ListView listProduct;
    ArrayList<String> records;
    String mname;

    protected void onCreate(Bundle savedInstanceState) {

        //TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.song_activity);
        context=this;
        records=new ArrayList<String>();
        listProduct=(ListView)findViewById(R.id.product_list);
        adapter=new CustomAdapter(context, R.layout.newlist_item,R.id.pro_name, records);
        listProduct.setAdapter(adapter);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null) {

            mname =(String) b.getString("movie_name");          
        }          
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        //create a LayoutTransition object       
        return true;
    }

    public void onStart(){

        super.onStart(); 
        //execute background task
        BackTask bt=new BackTask();
        bt.execute();
    }

    //background process to make a request to server and list product information
    private class BackTask extends AsyncTask<Void,Void,Void>{  

        protected void onPreExecute(){

            super.onPreExecute();
            pd = new ProgressDialog(context);
            pd.setTitle("Retrieving data");
            pd.setMessage("Please wait.");
            pd.setCancelable(true);
            pd.setIndeterminate(true);
            pd.show();       
        }

        protected Void doInBackground(Void...params){ 

            InputStream is=null;
            String result="";
            try{

                httpclient=new DefaultHttpClient();
                httppost= new HttpPost("http://necrecords.16mb.com/getsongslist.php?password="+mname);
                response=httpclient.execute(httppost);         
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }catch(Exception e){

                if(pd!=null)
                pd.dismiss();  //close the dialog if error occurs 
                Log.e("ERROR",e.getMessage());
            }

            //convert response to string
            try{

                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {

                    sb.append(line + "\n");
                }
                is.close();         
                result=sb.toString();
            }catch(Exception e){

                Log.e("ERROR", "Error converting result "+e.toString());
            }
            //parse json data
            try{

                JSONArray jArray =new JSONArray(result);
                for(int i=0;i<jArray.length();i++){

                    JSONObject json_data = jArray.getJSONObject(i);
                    String record = json_data.getString("allsongs")+"__"+json_data.getInt("test");
                    records.add(record);
                }           
            }
            catch(Exception e){

                Log.e("ERROR", "Error pasting data "+e.toString());
            }
            return null;
        }                   

        protected void onPostExecute(Void result){

            if(pd!=null) pd.dismiss(); //close dialog
            adapter.notifyDataSetChanged(); //notify the ListView to get new records
        }           
    }
} 

CustomAdapter.java

package com.example.telugump3;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CustomAdapter extends ArrayAdapter<String> {

    int groupid;
    ArrayList<String> records;
    Context context;

    public CustomAdapter(Context context, int vg, int id, ArrayList<String> records){

        super(context,vg, id, records);
        this.context=context;
        groupid=vg;
        this.records=records;
    }

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

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(groupid, parent, false);
        String[] row_items=records.get(position).split("__");
        TextView textName= (TextView) itemView.findViewById(R.id.pro_name);
        textName.setText(row_items[0]);
        TextView textPrice= (TextView) itemView.findViewById(R.id.pro_uprice);
        textPrice.setText(row_items[1]+"$");
        return itemView;
    }
}

logcat的

03-22 22:54:02.500: E/IMGSRV(7557): :0: PVRDRMOpen: TP3, ret = 37
03-22 22:54:02.500: E/IMGSRV(7557): :0: PVRDRMOpen: TP3, ret = 38
03-22 22:54:02.510: E/IMGSRV(7557): :0: PVRDRMOpen: TP3, ret = 38
03-22 22:54:02.510: E/IMGSRV(7557): :0: PVRDRMOpen: TP3, ret = 38
03-22 22:54:04.710: E/Launcher.Model(22911): Widget ComponentInfo{com.asus.calendar/com.android.calendar.widget2.CalendarAppWidgetPadProvider} has invalid dimensions (0, 0)
03-22 22:54:05.060: E/NetworkScheduler.SchedulerReceiver(16209): Invalid parameter app
03-22 22:54:05.060: E/NetworkScheduler.SchedulerReceiver(16209): Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
03-22 22:54:05.600: E/IMGSRV(7586): :0: PVRDRMOpen: TP3, ret = 37
03-22 22:54:05.600: E/IMGSRV(7586): :0: PVRDRMOpen: TP3, ret = 38
03-22 22:54:05.600: E/IMGSRV(7586): :0: PVRDRMOpen: TP3, ret = 38
03-22 22:54:05.600: E/IMGSRV(7586): :0: PVRDRMOpen: TP3, ret = 38
03-22 22:54:05.790: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 62
03-22 22:54:05.840: E/Save(22911): com.android.launcher3.Workspace$$Icicle.
03-22 22:54:05.850: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 41
03-22 22:54:05.900: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 37
03-22 22:54:06.060: E/IMGSRV(7654): :0: PVRDRMOpen: TP3, ret = 46
03-22 22:54:06.070: E/IMGSRV(7654): :0: PVRDRMOpen: TP3, ret = 50
03-22 22:54:06.070: E/IMGSRV(7654): :0: PVRDRMOpen: TP3, ret = 51
03-22 22:54:06.070: E/IMGSRV(7654): :0: PVRDRMOpen: TP3, ret = 51
03-22 22:54:06.070: E/IMGSRV(7654): :0: PVRDRMOpen: TP3, ret = 51
03-22 22:54:06.090: E/IMGSRV(7654): :0: PVRDRMOpen: TP3, ret = 53
03-22 22:54:06.130: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 40
03-22 22:54:06.190: E/[ParseTask](2945): [doInBackground] fail to retrieve url: https://play.google.com/store/apps/details?id=com.example.telugump3&hl=en-US
03-22 22:54:06.210: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 50
03-22 22:54:06.300: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 55
03-22 22:54:06.320: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 62
03-22 22:54:06.330: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 36
03-22 22:54:06.340: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 66
03-22 22:54:06.680: E/NetworkScheduler.SchedulerReceiver(16209): Invalid parameter app
03-22 22:54:06.680: E/NetworkScheduler.SchedulerReceiver(16209): Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
03-22 22:54:07.150: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 40
03-22 22:54:07.340: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 41
03-22 22:54:07.820: E/lights(560): [LED] open path fail.
03-22 22:54:08.000: E/ERROR(7654): Illegal character in query at index 54: http://necrecords.16mb.com/getsongslist.php?password=A AA E EEE
03-22 22:54:08.000: E/ERROR(7654): Error converting result java.lang.NullPointerException: lock == null
03-22 22:54:08.000: E/ERROR(7654): Error pasting data org.json.JSONException: End of input at character 0 of 
03-22 22:54:08.040: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 37
03-22 22:54:08.060: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 55
03-22 22:54:08.110: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 53
03-22 22:54:08.450: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 40
03-22 22:54:10.810: E/IMGSRV(185): :0: PVRDRMOpen: TP3, ret = 34
03-22 22:54:10.830: E/lights(560): [LED] open path fail.

現在我還有兩個疑問。

1)在SongsActivity.java中,我使用了從鏈接中的第一個Activity獲得的字符串來獲取所需的信息。 這是在url中使用字符串的正確方法嗎?

2)當我按返回按鈕返回第一個Activity時,ListView再次獲取數據,並且電影列表加倍。 有解決方案嗎?

這里發生了一些事情,我將盡力解決。

此日志條目可疑:

03-22 22:30:42.860: E/ERROR(6055): Illegal character in query at index 53: http://necrecords.16mb.com/getproducts.php?password=A AA E EEE

另外,從此日志中:

03-22 22:54:08.000: E/ERROR(7654): Error converting result java.lang.NullPointerException: lock == null

您可以看到您沒有從此PHP頁面獲得有效的響應。

此代碼塊引發異常:

//convert response to string
   try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
              sb.append(line + "\n");
        }
        is.close();         
        result=sb.toString();
   }catch(Exception e){
        Log.e("ERROR", "Error converting result "+e.toString());

我只是在瀏覽器中嘗試了該URL,然后它起作用了,因為瀏覽器會自動正確編碼該URL,如下所示:

http://necrecords.16mb.com/getproducts.php?password=A%20AA%20E%20EEE

我認為您只需要正確編碼URL,因為字符串包含空格。

String query = URLEncoder.encode(mname, "utf-8");

httppost= new HttpPost("http://necrecords.16mb.com/getsongslist.php?password="+query);
response=httpclient.execute(httppost);     

至於列表增加一倍的問題,您只需在每次執行AsyncTask時清除列表:

protected Void doInBackground(Void...params){ 

   InputStream is=null;
   String result="";
   try{

   records.clear(); //clear the list before re-populating

   httpclient=new DefaultHttpClient();
      httppost= new HttpPost("http://necrecords.16mb.com/getproducts.php");
   response=httpclient.execute(httppost);         
         HttpEntity entity = response.getEntity();
         is = entity.getContent();

   }catch(Exception e){

還有一件事要提到,您可能希望為每個Acitvity創建一個單獨的適配器。 現在,您正在為兩個活動使用相同的適配器。

在適配器的getView() ,您引用R.id.pro_nameR.id.pro_uprice ,但是您在兩個Activity中都使用了此適配器。 您的兩個活動都在其布局xml中包含這些元素嗎?

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

     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     View itemView = inflater.inflate(groupid, parent, false);
     String[] row_items=records.get(position).split("__");
     TextView textName= (TextView) itemView.findViewById(R.id.pro_name);
     textName.setText(row_items[0]);
     TextView textPrice= (TextView) itemView.findViewById(R.id.pro_uprice);
     textPrice.setText(row_items[1]+"$");
     return itemView;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM