Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Please help im new in java... im not able to display data in listview

PHP side

    <?
    $objConnect = mysql_connect("my server","username here"," my password");
    $objDB = mysql_select_db("db");

    $strSQL = "SELECT * FROM image WHERE 1  ";
    $objQuery = mysql_query($strSQL);
    $intNumField = mysql_num_fields($objQuery);
    $resultArray = array();
    while($obResult = mysql_fetch_array($objQuery))
    {
        $arrCol = array();
        for($i=0;$i<$intNumField;$i++)
        {
            $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
        }
        array_push($resultArray,$arrCol);
    }

    mysql_close($objConnect);

    echo json_encode($resultArray);
?>

I have 3 layout

main layout

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F3E70D" >

   <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:padding="10dip" >

       <TextView
           android:id="@+id/tvordername"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textColor="#000000"
           android:textStyle="bold"
           android:text="TextView" />

       <TextView
           android:id="@+id/textView2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="TextView" />

       <ListView
           android:id="@+id/listView1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" >
       </ListView>

   </LinearLayout>        

</ScrollView>

Second layout

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <ImageView
            android:id="@+id/ColImgPath"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/ColImgID"
            android:text="Column 1" />
        <TextView
            android:id="@+id/ColImgDesc"
            android:text="Column 2" />
    </TableRow>
</TableLayout>

Third layout is use to display more detail and single record

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView 
        android:id="@+id/fullimage"
        android:layout_width="match_parent"
        android:layout_height="245dp"/>
    <TextView 
        android:id="@+id/custom_full_order"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        >

    </TextView>
</LinearLayout>

Java side my complete code

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.android.library.DatabaseHandler;
import com.example.android.library.UserFunctions;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class OrderActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order);


        //listview
        final ListView lstview1 = (ListView)findViewById(R.id.listView1);

        String url = "my server address http:";

        try{
            JSONArray data = new JSONArray(getJSONUrl(url));

            final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String>map;

            for(int i= 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("ImageID", c.getString("ImageID"));
                map.put("ImageDesc", c.getString("ImageDesc"));
                map.put("ImagePath", c.getString("ImagePath"));
                MyArrList.add(map);
            }

            lstview1.setAdapter(new ImageAdapter(this,MyArrList));

            final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
            final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

            lstview1.setOnItemClickListener(new OnItemClickListener(){

                public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    View layout = inflater.inflate(R.layout.custom_fullorder_dialog, (ViewGroup) findViewById(R.id.fullimage));
                    ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
                try
                {
                    image.setImageBitmap(loadBitmap(MyArrList.get(position).get("Imagepath")));
                } catch (Exception e){
                    //if get error
                    image.setImageResource(android.R.drawable.ic_menu_report_image);
                }
                imageDialog.setIcon(android.R.drawable.btn_star_big_on);
                imageDialog.setTitle("View : " + MyArrList.get(position).get("comment"));
                imageDialog.setView(layout);
                imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });
                    imageDialog.create();
                    imageDialog.show();
                }

            });
        } catch(JSONException e){
            e.printStackTrace();
        }

    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list){

            context = c;
            MyArr = list;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return MyArr.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

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

            if(convertView == null){
                convertView = inflater.inflate(R.layout.activity_column, null);
            }
            //colimage
            ImageView imageView =(ImageView) convertView.findViewById(R.id.ColImgPath);
            imageView.getLayoutParams().height= 100;
            imageView.getLayoutParams().width= 100;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try
            {
                imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));

            } catch (Exception e){
                //if get error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            //colposition
            TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
            txtPosition.setPadding(10, 0, 0, 0);
            txtPosition.setText("ID : " + MyArr.get(position).get("ImageID"));

            //colpicname
            TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
            txtPicName.setPadding(50, 0, 0, 0);
            txtPicName.setText("DEesc : " + MyArr.get(position).get("ImageDesc"));

            return convertView;
        }

    }
    //get json code from url
    public String getJSONUrl(String url){
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try{
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while((line = reader.readLine()) != null){
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file...");
            }
        } catch (ClientProtocolException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    //get image resource from url
    private static final String TAG = "ERROR";
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    public static Bitmap loadBitmap(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in,out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSamplesize=1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        } catch (IOException e){
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }
        return bitmap;
    }

    private static void closeStream(Closeable stream){
        if(stream != null) {
            try{
                stream.close();
            } catch (IOException e){
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1){
            out.write(b, 0, read);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.order, menu);
        return true;
    }

}

my logcat

01-26 21:58:35.594: W/System.err(14298): org.json.JSONException: Value <? of type java.lang.String cannot be converted to JSONArray
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSON.typeMismatch(JSON.java:111)
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSONArray.<init>(JSONArray.java:96)
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSONArray.<init>(JSONArray.java:108)
01-26 21:58:35.594: W/System.err(14298):    at com.example.androidjhfong.OrderActivity.onCreate(OrderActivity.java:77)
01-26 21:58:35.594: W/System.err(14298):    at android.app.Activity.performCreate(Activity.java:5231)
01-26 21:58:35.599: W/System.err(14298):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
01-26 21:58:35.599: W/System.err(14298):    at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 21:58:35.599: W/System.err(14298):    at android.os.Looper.loop(Looper.java:136)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.main(ActivityThread.java:5139)
01-26 21:58:35.599: W/System.err(14298):    at java.lang.reflect.Method.invokeNative(Native Method)
01-26 21:58:35.599: W/System.err(14298):    at java.lang.reflect.Method.invoke(Method.java:515)
01-26 21:58:35.599: W/System.err(14298):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
01-26 21:58:35.599: W/System.err(14298):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
01-26 21:58:35.599: W/System.err(14298):    at dalvik.system.NativeStart.main(Native Method)
01-26 21:58:35.719: I/Timeline(14298): Timeline: Activity_idle id: android.os.BinderProxy@423fd758 time:785573323
share|improve this question
1  
what error do you get? or what exactly shows up wrong? –  aniri Jan 26 at 13:57
    
it did not run anything –  nic Jan 26 at 14:05
1  
The first line of your logcat tells it all. –  greenapps Jan 26 at 14:10
    
About your main layout: do not put a ListView in a ScrollView. –  greenapps Jan 26 at 14:11
    
where can i refer the example in my case? –  nic Jan 26 at 15:48

2 Answers 2

I think greenapps and MAGx2 have the right hints for the solution.

I'd like to add that it might be better to use a few open source libraries for the other things.

  • picasso for image downloading + displaying
  • gson for json parsing
  • okhttp for normal downloads

Also, don't use things like this:

imageView.getLayoutParams().height= 100;

It really messes up when you view on other devices with different DPI

share|improve this answer

You have real mess in your code. Firstly you shouldn't connect to web in main thread (it blocks app, cause "application not responding"). For fetching JSON I would recommend RoboSpice.

Secondly in ImageAdapter.getItem you should return MyArr.get(position) not position.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.