2016-12-04 49 views
2

我試圖找出如何獲得ratingBarListView在網上選定的ID,但他們幾乎都在另一個類上使用ListViewAdapterRatingAdapter。我不知道該怎麼辦,因爲我還不知道,所以我的所有課程都在MainActivity之間申報,包括ListViewANDROID - 在列表視圖中獲取選定的id ratingbar

我有一個TextViewRatingBarListView每個列表,

但問題是如何發送已填入服務器,而無需創建一個新的類ListViewAdapterRatingAdapterRatingBar每個列表?

這裏是我的全部代碼,它是如何工作的,以顯示每個列表上的TextViewRatingBar

public class Pertanyaan extends AppCompatActivity { 

    private String TAG = Pertanyaan.class.getSimpleName(); 

    private ProgressDialog pDialog; 
    private ListView lv; 
    private Button kirim; 
    private RatingBar rate; 

    ArrayList<HashMap<String, String>> contactList; 

    @Override 
    public void onBackPressed() { 
     super.onBackPressed(); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.pertanyaan); 
     contactList = new ArrayList<>(); 
     TextView textdosen=(TextView)findViewById(R.id.dosen); 
     TextView textmatkul=(TextView)findViewById(R.id.matkul); 
     final TextView txtrate=(TextView)findViewById(R.id.txtrating); 
     kirim = (Button)findViewById(R.id.btn); 
     rate=(RatingBar)findViewById(R.id.rating); 
     Bundle b=getIntent().getExtras(); 
     String dosen=b.getString("dosen"); 
     String matkul=b.getString("matkul"); 
     textdosen.setText(dosen); 
     textmatkul.setText(matkul); 
     lv = (ListView) findViewById(R.id.list); 
     new GetContacts().execute(); 
    } 

    private class GetContacts extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(Pertanyaan.this); 
      pDialog.setMessage("Menampilkan Pertanyaan..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler sh = new HttpHandler(); 

      // Making a request to url and getting response 
      String url = "http://flix.16mb.com/send_data.php"; 
      String jsonStr = sh.makeServiceCall(url); 

      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        JSONArray jsonObj = new JSONArray(jsonStr); 

        // looping through All Contacts 
        for (int i = 0; i < jsonObj.length(); i++) { 
         JSONObject c = jsonObj.getJSONObject(i); 

         String id = c.getString("id"); 
         String ask = c.getString("ask"); 

         HashMap<String, String> pertanyaans = new HashMap<>(); 

         pertanyaans.put("id", id); 
         pertanyaans.put("ask", ask); 

         contactList.add(pertanyaans); 
        } 
       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 

       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 

      return null; 
     } 
     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(
        Pertanyaan.this, contactList, 
        R.layout.list_pertanyaan, new String[]{"ask", "id"}, new int[]{R.id.ask, R.id.txtid}); 

      lv.setAdapter(adapter); 
     } 
    } 
} 

有人可以給我一個提示我應該怎麼辦?

+0

有人有想法嗎? – dondo

+0

首先,你的listview的setOnItemClickListener在哪裏? –

+0

這就是我應該問,我不知道在哪裏把setOnClickListener或onClickListener我的代碼,我一直試圖在任何代碼中添加,但我不能從logcat讀取錯誤,我需要一些想法 – dondo

回答

0

確定這裏是一個示例應用程序,以便它應該給你一些幫助:

所有你需要創建一個CustomAdapter因爲SimpleAdapter具有侷限性的第一位。其次,您需要使用RecyclerView而不是ListView。之後,您需要在用戶點擊您所做的列表時註冊點擊事件。對於這些事情,我們配備了以下幾點:

列表的型號:

public class CustomList { 
    private String id, ask; 

    public CustomList(String id, String ask) { 
     this.id = id; 
     this.ask = ask; 
    } 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public String getAsk() { 
     return ask; 
    } 

    public void setAsk(String ask) { 
     this.ask = ask; 
    } 
} 

則佈局爲每個列表項:

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

    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:padding="15dp" 
     android:layout_height="wrap_content"> 

     <TextView 
      android:text="TextView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/id_text" 
      android:layout_weight="4" /> 

     <TextView 
      android:text="TextView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/ask_text" 
      android:layout_weight="1" /> 
    </LinearLayout> 
</LinearLayout> 

則佈局RecyclerView

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="kostas.testexample.com.testexample.MainActivity"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/myRecyclerView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 
</LinearLayout> 

然後自定義適配器:

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder>{ 
    private List<CustomList> items; 
    private Context context; 

    public CustomAdapter(List<CustomList> items, Context context){ 
     this.items = items; 
     this.context = context; 
    } 

    @Override 
    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, parent, false); 
     return new CustomViewHolder(v); 
    } 

    @Override 
    public void onBindViewHolder(CustomViewHolder holder, int position) { 
     holder.itemId.setText(items.get(position).getId()); 
     holder.itemAsk.setText(items.get(position).getAsk()); 
    } 

    @Override 
    public int getItemCount() { 
     return items.size(); 
    } 

    @Override 
    public void onAttachedToRecyclerView(RecyclerView recyclerView) { 
     super.onAttachedToRecyclerView(recyclerView); 
    } 

    class CustomViewHolder extends RecyclerView.ViewHolder { 
     TextView itemId; 
     TextView itemAsk; 

     CustomViewHolder(View itemView) { 
      super(itemView); 
      itemId = (TextView)itemView.findViewById(R.id.id_text); 
      itemAsk = (TextView)itemView.findViewById(R.id.ask_text); 
     } 
    } 

} 

然後你加他們都用光MainActivity這樣的:

public class MainActivity extends AppCompatActivity { 
    private RecyclerView recyclerView; 
    private LinearLayoutManager layoutManager; 
    private URL url; 
    private HttpURLConnection httpURLConnection; 
    private CustomAdapter customAdapter; 
    private ProgressDialog pDialog; 
    private String id, ask; 
    private List<CustomList> customList = new ArrayList<>(); 
    private StringBuilder jsonResult; 
    private JSONObject jsonChildNode; 
    private JSONArray jsonResponse; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     recyclerView = (RecyclerView)findViewById(R.id.myRecyclerView); 
     layoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false); 
     recyclerView.setLayoutManager(layoutManager); 
     recyclerView.setHasFixedSize(true); 
     recyclerView.setNestedScrollingEnabled(false); 
     accessWebService(); 
     clickEvent(); 
    } 

    private void clickEvent() { 
     recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() { 
      @Override 
      public void onItemClick(View view, int position) { 
       Toast.makeText(MainActivity.this, "Item Clicked at position: " + position + " with id: " + customList.get(position).getId() + " and ask is: " + customList.get(position).getAsk(), Toast.LENGTH_SHORT).show(); 
      } 
     })); 
    } 


    public class JsonReadTask extends AsyncTask<String , Void, List<CustomList>> { 
     public JsonReadTask() { 
      super(); 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
      pDialog.setIndeterminate(true); 
      pDialog.setMessage("Please Wait"); 
      pDialog.setCancelable(false); 
      pDialog.setInverseBackgroundForced(true); 
      // pDialog.show(); 
     } 

     @Override 
     protected List<CustomList> doInBackground(String... params) { 
      try { 
       url = new URL(params[0]); 
       httpURLConnection =(HttpURLConnection) url.openConnection(); 
       httpURLConnection.connect(); 
       InputStream in = new BufferedInputStream(httpURLConnection.getInputStream()); 
       jsonResult = inputStreamToString(in, MainActivity.this); 
       jsonResponse = new JSONArray(jsonResult.toString()); 
       for (int i = 0; i < jsonResponse.length(); i++) { 
        jsonChildNode = jsonResponse.getJSONObject(i); 
        id = jsonChildNode.optString("id"); 
        ask = jsonChildNode.optString("ask"); 
        customList.add(new CustomList(id, ask)); 
       } 
      } catch (IOException | JSONException e) { 
       e.printStackTrace(); 
      } 
      return customList; 
     } 

     @Override 
     protected void onPostExecute(List<CustomList> customList) { 
      if(customList == null){ 
       Log.d("ERORR", "No result to show."); 
       return; 
      } 
      ListDrawer(customList); 
      pDialog.dismiss(); 
     } 


    } 

    public static StringBuilder inputStreamToString(InputStream is, Activity activity) { 
     String rLine; 
     StringBuilder answer = new StringBuilder(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     try { 
      while ((rLine = rd.readLine()) != null) { 
       answer.append(rLine); 
      } 
     } catch (Exception e) { 
      activity.finish(); 
     } 
     return answer; 
    } 

    private void ListDrawer(List<CustomList> customList) { 
     customAdapter = new CustomAdapter(customList, MainActivity.this); 
     customAdapter.notifyDataSetChanged(); 
     recyclerView.setAdapter(customAdapter); 
    } 

    public void accessWebService() { 
     JsonReadTask task = new JsonReadTask(); 
     task.execute("http://flix.16mb.com/send_data.php"); 
    } 
} 

,然後你需要產生以下結果爲RecyclerView

public class RecyclerItemClickListener implements OnItemTouchListener { 
    private OnItemClickListener mListener; 
    private OnLongItemClickListener mLongListener; 

    public interface OnItemClickListener { 
     public void onItemClick(View view, int position); 
    } 

    interface OnLongItemClickListener{ 
     boolean onLongItemClicked(int position); 
    } 

    private GestureDetector mGestureDetector; 

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) { 
     mListener = listener; 
     mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { 
      @Override 
      public boolean onSingleTapUp(MotionEvent e) { 
       return true; 
      } 
     }); 
    } 

    public RecyclerItemClickListener(Context context, OnLongItemClickListener listener) { 
     mLongListener = listener; 
     mGestureDetector = new GestureDetector(context, new GestureDetector.OnGestureListener() { 
      @Override 
      public boolean onDown(MotionEvent e) { 
       return false; 
      } 

      @Override 
      public void onShowPress(MotionEvent e) { 

      } 

      @Override 
      public boolean onSingleTapUp(MotionEvent e) { 
       return false; 
      } 

      @Override 
      public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 
       return false; 
      } 

      @Override 
      public void onLongPress(MotionEvent e) { 

      } 

      @Override 
      public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
       return false; 
      } 
     }); 
    } 

    @Override 
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { 
     View childView = view.findChildViewUnder(e.getX(), e.getY()); 
     if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { 
      mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); 
     } 
     return false; 
    } 

    @Override 
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { 
    } 

    @Override 
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { 

    } 
} 

的customListener:

enter image description here

但不要忘記添加到的build.gradle(模塊:應用程序)以下:

compile 'com.android.support:recyclerview-v7:25.0.1' 

,並在您的Manifest.xml許可:

<uses-permission android:name="android.permission.INTERNET"/> 

希望它可以幫助和給你一個提示如何做東西!

+0

但先生,如你所說,我需要一個ratingbar.onClickListener,所以 我應該創建一個新的適配器評級或我可以添加ratingClick到其中一個代碼? – dondo

+0

您可以在clickListener中使用customList.get(position).getId()作爲評級欄 –

相關問題