如何将onpostexecute方法的AsyncTask数据拆分成数组

时间:2016-08-16 04:39:12

标签: android android-asynctask

我想分割数据,以便我可以在不同的textView

中显示它 正如我在图像数据中给出的那样需要显示到这些不同的textview中 我能够在一个文本视图中获取数据,但不能在多个文本视图中获取数据

php代码:

 <?php
    require "init.php";
    $user_name=$_POST["login_name"];
    $user_pass=$_POST["login_pass"];

    $sql = "SELECT name,user_name,PRN,cast,dob,admission_category,nationality,permnent_address,local_address,roll_no,class,sub_cast,birth_place,mobile_no,email,branch  FROM user_info where user_name like '$user_name'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
      echo "name: " . $row["name"];

      }
    } else {[enter image description here][1]
        echo "login failed try again";
    }
    $conn->close();
    ?>*

ImportFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ImportFragment extends Fragment {
ImageView imageView2,imageView7;
    SQLiteDatabase db;

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


    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View myInflatedView = inflater.inflate(R.layout.fragment_import, container, false);
        Intent i = getActivity().getIntent();
        String name = i.getStringExtra("sey");
        Toast.makeText(getActivity(), "welcome: " + name, Toast.LENGTH_LONG).show();


        imageView2 = (ImageView) myInflatedView.findViewById(R.id.imageView2);
        TextView textView=(TextView)myInflatedView.findViewById(R.id.textView7);
        textView.setText(name);
        db=this.getActivity().openOrCreateDatabase("tedt.db", Context.MODE_PRIVATE,null);
        db.execSQL("create table if not exists tb (a blob)");

        Cursor c=db.rawQuery("select * from tb",null);
        getImage();
        if(c.moveToNext())
        {
            byte[] image =c.getBlob(0);
            Bitmap bmp= BitmapFactory.decodeByteArray(image,0,image.length);
            imageView2.setImageBitmap(bmp);

            Toast.makeText(getActivity(),"get success",Toast.LENGTH_SHORT).show();
        }
        Button button=(Button)myInflatedView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                fm.beginTransaction().replace(R.id.contentframe,new ExportFragment()).commit();

            }
        });

    return myInflatedView;
    }

    public void getImage()
    {
        Cursor c=db.rawQuery("select * from tb",null);
        if(c.moveToNext())
        {
            byte[] image =c.getBlob(0);
            Bitmap bmp= BitmapFactory.decodeByteArray(image,0,image.length);
            imageView2.setImageBitmap(bmp);

            Toast.makeText(getActivity(),"get success",Toast.LENGTH_SHORT).show();
        }
    }
}

BackgroundTask

    class BackgroundTask extends AsyncTask<String, Void, String> {
        AlertDialog alertDialog;
        TextView textView1;

        Context ctx;
        BackgroundTask(Context ctx)
        {
            this.textView1=textView1;
            this.ctx=ctx;
        }
        @Override
        protected void onPreExecute()
        {
            alertDialog=new AlertDialog.Builder(ctx).create();
            alertDialog.setTitle("Login Information...");

        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {

            if(result.equals("registration success")) {
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
            }
            else
            {
               // alertDialog.setMessage(result);
               // alertDialog.show();
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                Intent intent=new Intent(ctx,drawer.class);
               intent.putExtra("sey",result);
               String a=result;
                ctx.startActivity(intent);
            }
        }

        @Override
        protected String doInBackground(String... params) {
            String reg_url="http://10.0.2.2/webapp/register.php";
            String login_url="http://10.0.2.2/webapp/login.php";

            String method=params[0];
            if(method.equals("register"))
            {
                String name=params[1];
                String user_name=params[2];
                String user_pass=params[3];
                try {
                    URL url=new URL(reg_url);
                    HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    OutputStream os=httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
                    String data= URLEncoder.encode("user","UTF-8")+ "="+URLEncoder.encode(name,"UTF-8")+"&"+
                            URLEncoder.encode("user_name","UTF-8")+ "="+URLEncoder.encode(user_name,"UTF-8")+"&"+
                            URLEncoder.encode("user_pass","UTF-8")+ "="+URLEncoder.encode(user_pass,"UTF-8");
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    os.close();
                    InputStream is=httpURLConnection.getInputStream();
                    is.close();
                    return "registration success";
                }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else if(method.equals("login"))
            {

                String login_name=params[1];
                String login_pass=params[2];
                try {
                    URL url=new URL(login_url);
                    HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    OutputStream outputStream=httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                    String data=URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                            URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();

                    InputStream inputStream=httpURLConnection.getInputStream();
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                    String response="";
                    String line="";
                    while ((line=bufferedReader.readLine())!=null)
                    {
                        response+=line;
                    }

                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    return response;

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }

1 个答案:

答案 0 :(得分:0)

如果数据长度和结构未知

您可以像以下一样显示它。

  1. 数据的结构应该类似于(XML,Json)

    { “名称”:“托马斯”, “时代”:12, “地址”:“伦敦” }

  2. 每个元素都应包含一个键,以便您可以使用键生成TextView(用于标签)。

    1. TextView将以动态方式生成,因为数据长度在json数据中是动态的。 (就像这个how to add dynamic array of textviews to a tablelayout through table row in android?
    2. 但请记住,如果android中显示的某些数据没有任何自定义样式。布局不仅难看,而且难以理解。如果来自服务器的所有数据(包括服务器的项目ID或敏感信息)都显示在移动设备上,则可能容易受到攻击。为了最好地使用数据和您的安全,您应该逐个将数据提取到每个文本视图中(findViewById)。如果这个方法对你来说很麻烦,你可以告别它并使用android数据绑定(https://developer.android.com/topic/libraries/data-binding/index.html)。 但是,此库尚未与JDK 8兼容。使用前请三思而后行。