2015-07-12 2 views
-1

Извините, если вы найдете этот вопрос повторяющимся. Но я посмотрел на все другое решение, и я не могу найти решение моей проблемы с применением notifyDataSetChanged().Невозможно применить пользовательский адаптер notifyDataSetChanged()

Мой текущий код: От VenueSQL1 Активность Я зову обычая Adapter

protected void onPostExecute(Void result) { 
     try{ 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 

     if(count==1){ 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
      count++; 
     } 


     state = lv.onSaveInstanceState(); 
     final ListAdapter myadapter=new customAdapterVenues(VenueSQL1.this,contactList1); 

      runOnUiThread(new Runnable() { 
       public void run() { 

        lv.setAdapter(myadapter); 
       } 
      }); 
      lv.onRestoreInstanceState(state); 
     } 

customAdapterVenues

/** * сотворяемые Shubham на 6/21/2015. */

public class customAdapterVenues extends ArrayAdapter<HashMap<String, String>>{ 

private Context mcontext; 
public String unique_id1,Cost1,Type1,Name1; 
public ArrayList<Integer> flags=new ArrayList<>(); 
static final ArrayList<Integer> set=new ArrayList<>(); 
String android_id,android_id1; 
String unique_id,Name,Type="weddinghalls",Cost; 
int flag=0; 
int pos=0; 





public customAdapterVenues(Context context, ArrayList<HashMap<String, String>> main) { 

    super(context, R.layout.list_item, main); 
    // this.notifyDataSetChanged(); 
    mcontext=context; 


} 

public View getView(final int position, View convertView, ViewGroup parent) { 
    LayoutInflater shubhamsinflator=LayoutInflater.from(getContext()); 
    View customview=shubhamsinflator.inflate(R.layout.list_item, parent, false); 
    android_id = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); 
    //this.notifyDataSetChanged(); 
    try { 
     flag=0; 
     flags.add(position,0); 
     // set.add(position,0); 


     HashMap<String, String> map = (HashMap<String, String>) getItem(position); 

     final String name1 = map.get("Name"); 
     Name=name1; 
     Log.d("flag:",String.valueOf(position)); 

     String address1 = map.get("Area"); 
     String image = map.get("Image"); 
     String cost = map.get("Cost"); 
     // if(set.get(position)==0) { 
      unique_id = map.get("UniqueId"); 
      // set.set(position, 1); 
     //} 
     android_id1=map.get("UserId"); 
     Cost=cost; 
     final String phone = map.get("Telephone"); 
     //phone=phone.replace(" ",""); 
     // String name1 = map.get("name"); 
     //String name1=getItem(position). 
     TextView shubhamsText = (TextView) customview.findViewById(R.id.name); 
     TextView shubhamsText2 = (TextView) customview.findViewById(R.id.address); 
     TextView shubhamsText3 = (TextView) customview.findViewById(R.id.price); 
     TextView shubhamsText4 = (TextView) customview.findViewById(R.id.price1); 
     ImageView shubhamsimage = (ImageView) customview.findViewById(R.id.imageView2); 
     com.example.shubham.myapp.CircleImageView call = (com.example.shubham.myapp.CircleImageView) customview.findViewById(R.id.but); 
     call.setOnClickListener(
       new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         // Intent callIntent = new Intent(Intent.ACTION_CALL); 
         //callIntent.setData(Uri.parse("tel:" + phone)); 
         //getContext().startActivity(callIntent); 
         myDialog(name1, phone); 


        } 


       } 
     ); 


     shubhamsText.setText(name1); 
     shubhamsText2.setText(address1); 
     //cost = cost.replace("Per Plate", ""); 
     shubhamsText3.setText("Rs. "+cost); 
     shubhamsText4.setText("Per Plate"); 
     if (cost.equals("0")) { 
      shubhamsText3.setText("Price on"); 
      shubhamsText4.setText("Request"); 
      // shubhamsText3.setText(" "); 

     if (!image.equals("NA")) 
      Picasso.with(getContext()).load(image).into((ImageView) customview.findViewById(R.id.imageView2)); 
     else 
      shubhamsimage.setImageResource(R.drawable.ina); 

     //shubhamsimage.setImageResource(p); 
    }catch (Exception e){ 
     Log.d("Hello","hello"); 

    } 
     return customview; 

    //return super.getView(position, convertView, parent); 
} 
private ProgressDialog pDialog; 
private AlertDialog.Builder dialogBuilder; 
public static final int CONNECTION_TIMEOUT=1000*15; 
public static final String SERVER_ADDRESS="http://shubhamsapp.esy.es/"; 

private void myDialog(String name1, final String phone) 
{ 
    dialogBuilder=new AlertDialog.Builder(getContext()); 
    dialogBuilder.setTitle(name1+"\n"+" " +phone); 

    dialogBuilder.setPositiveButton("Call", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int w) { 
      Intent callIntent = new Intent(Intent.ACTION_CALL); 
      callIntent.setData(Uri.parse("tel:" + phone)); 
      getContext().startActivity(callIntent); 
     } 
    }); 
    dialogBuilder.setNegativeButton("Don't Call",new DialogInterface.OnClickListener(){ 
     @Override 
     public void onClick(DialogInterface dialog, int w) { 
      //Intent callIntent = new Intent(Intent.ACTION_CALL); 
      //callIntent.setData(Uri.parse("tel:" + phone)); 
      //getContext().startActivity(callIntent); 
     } 
    }); 
    AlertDialog dialog=dialogBuilder.create(); 
    //dialog.setTitle("Hey"); 
    dialog.show(); 


} 

}

Это работает для меня. Но проблема заключается в том, что каждый элемент времени добавляется в список, когда адаптер начинает печатать из начальной позиции, создавая небольшое отставание в приложении. Я хочу, чтобы он начал отображать из элементов списка, которые были добавлены аккуратно, а предыдущие элементы остаются такими, какими они есть, и на них не влияет. Могу ли я сделать это с notifyDataSetChanged и где его добавить, поскольку я пробовал везде, но он не работает. Также иногда я получаю сообщение об ошибке «the-content-of-the-adapter-has-changed-but-listview-did-not-receive-a-notification». Для этого я добавил поток в активность VenueSQL1. Правильно ли это?

ответ

0

для отстающих вашей программы вы можете использовать ViewHolder шаблон внутри метода GetView и всякий раз, когда вы добавляете новые данные вы Список_массивы Jst использовать вас адаптер объект с notifyDataSetChanged() он будет работать

+0

Спасибо. Вы решили мою проблему, которую я начал с начала. – shubhamgarg1

0

Просто добавьте новый элемент в структуру данных в вашем случае к hashmap, всякий раз, когда добавляется новый элемент.

И не забудьте позвонить. myadapter.notifysetdatachanged(); Он будет отображать новые данные в вашем списке.

+0

Я добавил, что в этот список. Но myadapter.notifyDataSetCahanged() даже не перекомпонован компилятором. Он может применяться только в классе customadaptervenues, используя this.notifydatasetcanged(). Но я не могу понять, где его применять. – shubhamgarg1

+0

Вы можете использовать его в том же классе, где вы определили свой адаптер. – logan

+0

Я пробовал, но это было бесполезно. – shubhamgarg1