1

My Application works like this. First, MainActivity.java displays a list of movies fetched from mysql database. When a movie is clicked in the list, SongsActivity.java opens and displays the list of songs in that particular movie. The first Activity works fine but when I clicked on the movie, second Activity opens blank! No fetching is being done! Below is my code, please help me.

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.

Now I have two more doubts.

1) In SongsActivity.java, I have used a string which I have got from first Activity in a link to fetch the required info. Is that the correct way to use a string in url?

2) When I press back button to return to first Activity, the ListView fetches the data again and the movie list doubles. Is there a solution for this?

2
  • Have you checked by using log messages correct value of movie_name is received at SongsActivity.java? Commented Mar 22, 2015 at 17:22
  • Yes sir, I have created a TextView and set the received movie_name to it. It worked. The app is able to receive the movie name from first activity. Commented Mar 22, 2015 at 17:28

1 Answer 1

1

There are a few things going on here, I'll try to address what I can.

This log entry is suspicious:

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

Also, from this log:

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

You can see that you are not getting a valid response from this PHP page.

This code block is throwing an exception:

//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());

I just tried the URL in a browser, and it worked, since the browser automatically encodes the url properly, like this:

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

I think that you just need to properly encode the URL since the string contains spaces.

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

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

As for the issue of your list getting doubled, you could just clear the list each time the AsyncTask executes:

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){

One more thing to mention, you will probably want to create a separate Adapter for each Acitvity. As it is now, you are using the same Adapter for both Activities.

In your Adapter's getView(), you reference R.id.pro_name and R.id.pro_uprice, but you're using this Adapter in both of your Activities. Do both of your Activities contain these elements in their layout 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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm using same adapter for both the Activities sir, and both of them contain pro_name and pro_uprice in them. When the second activity opens, It doesn't even shows the loading box like the first activity.
Just updated the answer, I think the main problem was that the string contains spaces, and needs to be properly encoded.
It worked sir..!! Thank you soooooooooo much...you are such a genius!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.