我对Android编程的学习有一个小问题。 我已经在谷歌搜索解决方案,但我找不到它,我需要你的帮助。
我遵循了一个教程,使用mySQL数据库进行基本的CRUD操作。
以下是源代码:
package net.simplifiedlearning.myheroapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.view.View.GONE;
public class MainActivity extends AppCompatActivity {
private static final int CODE_GET_REQUEST = 1024;
private static final int CODE_POST_REQUEST = 1025;
EditText editTextHeroId, editTextNom, editTextprenom;
RatingBar ratingBar;
Spinner spinnerTeam;
ProgressBar progressBar;
ListView listView;
Button buttonAddUpdate;
List<Hero> heroList;
boolean isUpdating = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
editTextNom = (EditText) findViewById(R.id.editTextNom);
editTextprenom = (EditText) findViewById(R.id.editTextPrenom);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);
buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
listView = (ListView) findViewById(R.id.listViewHeroes);
heroList = new ArrayList<>();
buttonAddUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isUpdating) {
updateHero();
} else {
createHero();
}
}
});
readHeroes();
}
private void createHero() {
String nom = editTextNom.getText().toString().trim();
String prenom = editTextprenom.getText().toString().trim();
int rating = (int) ratingBar.getRating();
String team = spinnerTeam.getSelectedItem().toString();
if (TextUtils.isEmpty(nom)) {
editTextNom.setError("Please enter name");
editTextNom.requestFocus();
return;
}
if (TextUtils.isEmpty(prenom)) {
editTextprenom.setError("Please enter real name");
editTextprenom.requestFocus();
return;
}
HashMap<String, String> params = new HashMap<>();
params.put("nom", nom);
params.put("prenom", prenom);
params.put("rating", String.valueOf(rating));
params.put("teamaffiliation", team);
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_CREATE_HERO, params, CODE_POST_REQUEST);
request.execute();
}
private void readHeroes() {
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null, CODE_GET_REQUEST);
request.execute();
}
private void updateHero() {
String id = editTextHeroId.getText().toString();
String nom = editTextNom.getText().toString().trim();
String prenom = editTextprenom.getText().toString().trim();
int rating = (int) ratingBar.getRating();
String team = spinnerTeam.getSelectedItem().toString();
if (TextUtils.isEmpty(nom)) {
editTextNom.setError("Please enter name");
editTextNom.requestFocus();
return;
}
if (TextUtils.isEmpty(prenom)) {
editTextprenom.setError("Please enter real name");
editTextprenom.requestFocus();
return;
}
HashMap<String, String> params = new HashMap<>();
params.put("id", id);
params.put("nom", nom);
params.put("prenom", prenom);
params.put("rating", String.valueOf(rating));
params.put("teamaffiliation", team);
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_UPDATE_HERO, params, CODE_POST_REQUEST);
request.execute();
buttonAddUpdate.setText("Add");
editTextNom.setText("");
editTextprenom.setText("");
ratingBar.setRating(0);
spinnerTeam.setSelection(0);
isUpdating = false;
}
private void deleteHero(int id) {
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_DELETE_HERO + id, null, CODE_GET_REQUEST);
request.execute();
}
private void refreshHeroList(JSONArray heroes) throws JSONException {
heroList.clear();
for (int i = 0; i < heroes.length(); i++) {
JSONObject obj = heroes.getJSONObject(i);
heroList.add(new Hero(
obj.getInt("id"),
obj.getString("nom"),
obj.getString("prenom"),
obj.getInt("rating"),
obj.getString("teamaffiliation")
));
}
HeroAdapter adapter = new HeroAdapter(heroList);
listView.setAdapter(adapter);
}
private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
String url;
HashMap<String, String> params;
int requestCode;
PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(GONE);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
refreshHeroList(object.getJSONArray("heroes"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
class HeroAdapter extends ArrayAdapter<Hero> {
List<Hero> heroList;
public HeroAdapter(List<Hero> heroList) {
super(MainActivity.this, R.layout.layout_hero_list, heroList);
this.heroList = heroList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
TextView textViewDelete = listViewItem.findViewById(R.id.textViewDelete);
final Hero hero = heroList.get(position);
textViewName.setText(hero.getNom());
textViewUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isUpdating = true;
editTextHeroId.setText(String.valueOf(hero.getId()));
editTextNom.setText(hero.getNom());
editTextprenom.setText(hero.getPrenom());
ratingBar.setRating(hero.getRating());
spinnerTeam.setSelection(((ArrayAdapter<String>) spinnerTeam.getAdapter()).getPosition(hero.getTeamaffiliation()));
buttonAddUpdate.setText("Update");
}
});
textViewDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete " + hero.getNom())
.setMessage("Are you sure you want to delete it?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteHero(hero.getId());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
return listViewItem;
}
}
}
我想获得相同的结果,但我想在另一个活动中获取listView。 怎么办呢?
答案 0 :(得分:0)
将所有数据存储在Object中,并使用Serializable将其发送到下一个活动。 在Hero类中实现Serializable。 并将其传递给适配器。
答案 1 :(得分:0)
创建新活动并设置UI后,在单击按钮获取数据并传递给ListView活动时,附加一个侦听器来捕获事件:
buttonAddUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isUpdating) {
updateHero();
} else {
createHero();
}
}
});
然后在createHero()
方法内,获取所需信息并通过附加内容传递给 YourListViewActivity 意图。
public void createHero() {
String heroId = editTextHeroId .getText().toString();
Intent intent = new Intent(MainActivity.this, YourListViewActivity.class);
intent.putExtra("hero_id", heroId);
//Add more if you want
startActivity(intent);
}
然后转到 YourListViewActivity 的onCreate()
,从其他内容中获取所需信息:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String heroId = getIntent().getStringExtra("hero_id");
//Then populate it to your ListView
}
高级解决方案:创建模型类 Hero ,并实现 Serializable ,通过Intent放置整个类实例,而不传递每个元素。