2017-03-01 1 views
0

로그인 화면과 정보가있는 두 번째 화면이있는 앱을 수행하고 있습니다.처음 로그인 화면에 빈 활동이로드됩니다.

사용자 이름과 암호는 JSON에서 확인합니다. 그 후, 의도는 활동을 ApprovalsActivity.class로 건너 뛰며, 이는 두 번째 JSON의 항목을 LISTVIEW에 표시합니다.

그것은 당신이 로그인 한 후이 작업을 보여주는 헬프 데스크 시스템 같아요.

모든 작품 (감사 유래의 xD) 만 두 번째 시간 이후 사용자가 로그인. 그래서

, 때를 먼저 로그인을 클릭하면 앱이 활동을 건너 뛰지 만 빈 칸으로 이동합니다. 뒤로 버튼을 클릭하고 다시 로그인하면 목록보기의 항목이 나타납니다.

아무도 도와 줄 수 없습니까? JSON으로 더 복잡한 작업을 한 것은 이번이 처음입니다.

MainActivity (LoginScreen) :

public class MainActivity extends AppCompatActivity { 

EditText usernameWidget; 
EditText passwordWidget; 

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

    usernameWidget = (EditText) findViewById(R.id.tv_username); 
    passwordWidget = (EditText) findViewById(R.id.tv_password); 

}// END ON CREATE 

public class DownloadTask extends AsyncTask<String, Void, String> { 
    String message = "message"; 
    String loginSuccess; 
    String pessoaFisicaId = "PessoaFisicaId"; 


    @Override 
    protected String doInBackground(String... urls) { 
     String result = ""; 
     URL url; 
     HttpURLConnection urlConnection = null; 

     try { 
      url = new URL(urls[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      InputStream inputStream = urlConnection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(inputStream); 

      int data = reader.read(); 

      while (data != -1){ 
       char current = (char) data; // each time creates a char current 

       result += current; 

       data = reader.read(); 
      } 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return result; 
    } // END doInBackground 


    //Method called when the doInBack is complete 
    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     try { 
      JSONObject jsonObject = new JSONObject(result); 

      loginSuccess = jsonObject.getString("success"); 
      pessoaFisicaId = jsonObject.getString("PessoaFisicaId"); 
      message = jsonObject.getString("message"); 

     }catch(JSONException e) { 
      e.printStackTrace(); 
     }// END CATCH 

     if (loginSuccess.contains("true")){ 
      Intent intent = new Intent(getApplicationContext(), ApprovalsActivity.class); 
      intent.putExtra("pessoaFisicaId", pessoaFisicaId); 
      startActivity(intent); 
     }else if (loginSuccess.contains("false")){ 
      Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); 
     } 
    }// END POST EXECUTE 
}// END Download Task 

public void login(View view) { 
    String user = usernameWidget.getText().toString(); 
    String pass = passwordWidget.getText().toString(); 

    String stringJSON = "URLHIDDENlogin=" + user + "&senha=" + pass; 
    DownloadTask task = new DownloadTask(); 
    task.execute(stringJSON); 
}// END LOGIN 

ApprovalsActivity (로그인 화면이 올바른 사용자 및 암호를 통과 한 후) :

public class ApprovalsActivity extends AppCompatActivity { 

public static List<String> getChamadoStringListFromJsonArray = new ArrayList<String>(); 
public static List<String> getSolicitanteStringListFromJsonArray = new ArrayList<String>(); 
public static List<String> getItemStringListFromJsonArray = new ArrayList<String>(); 

public static String chamado; 
public static String solicitante; 
public static String itemDeCatalogo; 

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

    Intent intent = getIntent(); 
    String pessoaFisicaId = intent.getExtras().getString("pessoaFisicaId"); 

    String stringJSON = "URLHIDDEN" + pessoaFisicaId; 
    DownloadTask task = new DownloadTask(); 
    task.execute(stringJSON); 

    ListView listApprovals = (ListView) findViewById(R.id.list_aprovacoes); 
    CustomizedListClass customizedListView = new CustomizedListClass(ApprovalsActivity.this); 
    listApprovals.setAdapter(customizedListView); //Layout inflator 

    listApprovals.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 


     } 
    }); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.aprovacoes_menu, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    return super.onOptionsItemSelected(item); 
} 

public class DownloadTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... urls) { 
     String result = ""; 
     URL url; 
     HttpURLConnection urlConnection = null; 

     try { 
      url = new URL(urls[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      InputStream inputStream = urlConnection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(inputStream); 

      int data = reader.read(); 

      while (data != -1){ 
       char current = (char) data; // each time creates a char current 

       result += current; 

       data = reader.read(); 
      } 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 


     try { 
      JSONObject jsonObject = new JSONObject(result); 
      JSONArray jsonarray = jsonObject.getJSONArray("dados"); 

      for (int i = 0; i < jsonarray.length(); i++) { 
       JSONObject jsonPart = jsonarray.getJSONObject(i); 
       chamado = jsonPart.getString("Chamado"); 
       solicitante = jsonPart.getString("Solicitante"); 
       itemDeCatalogo = jsonPart.getString("ItemDeCatalogo"); 

       getChamadoStringListFromJsonArray.add(chamado); 
       Log.i("****getChamado", String.valueOf(getChamadoStringListFromJsonArray)); 
       getSolicitanteStringListFromJsonArray.add(solicitante); 
       Log.i("****getsolicitante", String.valueOf(getSolicitanteStringListFromJsonArray)); 
       getItemStringListFromJsonArray.add(itemDeCatalogo); 
       Log.i("****getItem", String.valueOf(getItemStringListFromJsonArray)); 

      } 
     }catch(JSONException e) { 
      e.printStackTrace(); 
     }// END CATCH 

     return result; 
    } // END doInBackground 

    //Method called when the doInBack is complete 
    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 


    }// END POST EXECUTE 
}// END Download Task 

}

CustomizedListClass (목록의 항목을 표시) :

public class CustomizedListClass extends BaseAdapter { 

Context context; 
LayoutInflater mLayoutInflater; 

TextView txtChamado; 
TextView txtSolicitante; 
TextView txtItemDeCatalogo; 

public CustomizedListClass(Context context) { 
    this.context = context; 
    //Instantiate the layoutinflater object to use the layout inflater service on a object context 
    mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public int getCount() { //count the objects 
    return getChamadoStringListFromJsonArray.size(); //return the length of the array 
} 

@Override 
public Object getItem(int position) { //gets an specific item in the array 
    return position; //return the specific value in array animalImages in the position position(variable) 
} 

@Override 
public long getItemId(int position) { //returns the item ID of our objects 
    return position; //The ID is the position of the item in the array 
} 

@Override 
public View getView(final int position, View view, final ViewGroup parent) { 

    view = mLayoutInflater.inflate(R.layout.customized_list_view, null); 

    txtChamado = (TextView) view.findViewById(R.id.txtChamado); 
    txtSolicitante = (TextView) view.findViewById(R.id.txtSolicitante); 
    txtItemDeCatalogo = (TextView) view.findViewById(R.id.txtItemDeCatalogo); 


    String oldChamado = txtChamado.getText().toString(); 
    String newChamado = getChamadoStringListFromJsonArray.get(position); 
    txtChamado.setText(oldChamado + newChamado); 

    String oldSolicitante = txtSolicitante.getText().toString(); 
    String newSolicitante = getSolicitanteStringListFromJsonArray.get(position); 
    txtSolicitante.setText(oldSolicitante + newSolicitante); 

    String oldItemDeCatalogo = txtItemDeCatalogo.getText().toString(); 
    String newItemDeCatalogo = getItemStringListFromJsonArray.get(position); 
    txtItemDeCatalogo.setText(oldItemDeCatalogo + newItemDeCatalogo); 


    view.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // TODO Auto-generated method stub 
      Toast.makeText(context, "You Clicked "+ getChamadoStringListFromJsonArray.get(position), Toast.LENGTH_LONG).show(); 

     } 
    }); 

    return view; 
}// END METHOD 
} 

해결 방법 :

추가 customListList.notifyDataSetChanged(); OnPostExecute에 대해

getItemStringListFromJsonArray.add(itemDeCatalogo); 
       Log.i("****getItem", String.valueOf(getItemStringListFromJsonArray)); 

이므로 목록 뷰 어댑터는 변경된 사항을 알고 업데이트해야합니다.

또한 선언

CustomizedListClass customizedListView; 

를 외부에서 OnCreate.

+0

첫 번째 시도에서 올바르게 작동하지만 연속 시도는하지 않습니까? – Remario

+0

반대로. 첫 번째 시도는 빈 화면으로 이동합니다. 두 번째는 오른쪽 화면 인 listview로 이동합니다. – BlitzkriegBlue

+0

화면에서 전환을 살펴 보셨습니까? 보기 A (로그인)에서보기 B (목록보기)로 전환 할 때 모든 것이 올바르게 설정 되었습니까? 두 번 똑같은 일을합니까? 로깅 (System.out.println() 또는 Log.e ("debugger", [message]))을 추가하여 어떤 것이 올바르게 작동하지 않는 것을 볼 수 있습니다. – Zoe

답변

0

listview가 초기화 된 후 작업을 실행하려고 시도 했습니까? 또는 onPoastExecutre에서 작업 종료 후 어댑터 notifyDataSetChanged를 호출하려고 시도하십시오.

+0

로그인을 클릭하면 인 텐트가 listview가있는 활동으로 점프합니다. notifyDataSetChanged를 사용하지 않았습니다. 해야합니까? (나는 그것을 올바르게 사용하는 방법을 기억하지 못하지만 어떤 문제를 해결한다는 것을 알고있다). – BlitzkriegBlue

+0

notifyDataSetChanged를 호출하면 문제가 해결된다고 생각합니다. – Luci

+0

귀하의 작업은 활동이 생성되고 목록이 이미로드 된 후에 종료 될 가능성이 큽니다. 작업이 끝나더라도 데이터 목록에 새 데이터가 포함되어 있으면 목록보기/어댑터에 데이터 세트가 변경되었다는 알림을 받아야하며 이로 인해 목록보기에서 "새"항목을로드하게됩니다. – Luci

관련 문제