【问题标题】:The method add(String) is undefined for the type String (JSONArray)对于 String (JSONArray) 类型的方法 add(String) 未定义
【发布时间】:2023-03-26 19:15:01
【问题描述】:

在使用 MySQL 查询从 PHP 文件中接收数据后,我想用数据填充两个数组。 第一个数组有效:

results.add((String) json_data.get("product") + "\n" + json_data.get("owner"));

但是当我添加第二个数组时:

mysql_id.add((String) json_data.get("id")); 

Eclipse 显示错误:

方法 add(String) 没有为 String 类型定义

没有可用的建议,我不知道问题所在。 我到处都有“mysql_id”声明为“结果”,但它不起作用!

感谢您的帮助!

这是完整的代码:

package de.maartenfricke.coffeebar;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;

public class Overview extends Activity {
    InputStream is;
    ArrayList<String> results = new ArrayList<String>();
    ArrayList<String> mysql_id = new ArrayList<String>();
    JSONObject json_data;
    JSONObject json_data_2;
    Boolean dataComplete = false;   

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

    Bundle zielkorb = getIntent().getExtras();
    String text2 = zielkorb.getString("datenpaket1");

    Context context = getApplicationContext();
    CharSequence text = "Sie haben soeben einen " + text2 + " bestellt";
    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();


    getData();        
    while(!this.dataComplete) {// es soll solange gewartet werden bis die ArrayList ganz gefüllt ist und die Abfrage beendet wurde
        //ProgressDialog pd = ProgressDialog.show(Overview.this,"Loading...","Frage Daten von Server ab...");
    try {
        Thread.sleep(50);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }   
    //pd.demiss();
    this.fillList(); 



}

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

public void getData() {
    Thread t = new Thread() {   //Setzte Tread
    private String result = ""; //Setze Variable String für die Ergebnisse
    private String mysql_id = "";   //Setze Variable mysql_id für mysql_id
    public void run() {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();   //Definiere Arrayliste
    try {
        HttpClient httpclient = new DefaultHttpClient(); //http client ünterstützt das indirekte verbinden mit webseiten ohne Browser und upload, download etc.
        HttpPost httppost = new HttpPost("http://192.168.178.35/getAllOrders.php"); //Rufe Link auf
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } 
    catch(Exception e) {    //Wenn ein Fehler auftritt:
        Log.e("log_tag", "Fehler bei der http Verbindung "+e.toString());
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        mysql_id=sb.toString();
        result=sb.toString();

    }
    catch(Exception e) {    //Wenn ein Fehler auftritt:
        Log.e("log_tag", "Error converting result "+e.toString());
    }

    try {
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++) {
            json_data = jArray.getJSONObject(i);
            results.add((String) json_data.get("product") + "\n" + json_data.get("owner"));
            //mysql_id.add((String) json_data.get("id")); 
        }       
        dataComplete = true;
    }
    catch(JSONException e) { //Wenn ein Fehler auftritt:
    Log.e("log_tag", "Error parsing data "+e.toString());
    }
}       
};
t.start();
}

public void fillList() {
    //this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));

    ScrollView sv = new ScrollView(this);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);

    for (int i = 0; i < results.size(); i++) {
        String tag = results.get(i);
        final CheckBox cb = new CheckBox(this);
        cb.setText(tag);
        cb.setTag("checkbox");
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
                // TODO Auto-generated method stub 
                if (buttonView.isChecked()) { 
                    try {
                        setOrderFinish(cb.getId());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else { 
                    Toast.makeText(getBaseContext(), "UnChecked: " + buttonView + isChecked, 
                    Toast.LENGTH_SHORT).show(); 
                }
            }
        }); 
        ll.addView(cb);
    }
    this.setContentView(sv);
}

public void setOrderFinish(int product_id) throws IOException {
    URL url = new URL("http://192.168.178.35/setOrderAsFinished.php?id="+product_id);
    URLConnection urlConnection = url.openConnection();
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    try {
        Context context = getApplicationContext();
        CharSequence text = "Finished: " + product_id;
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show(); 
    } finally {
        in.close();
    }
}
}

【问题讨论】:

标签: android mysql arrays json add


【解决方案1】:

您的 mysql_id 被重新定义为匿名线程的成员:

private String mysql_id = "";   //Setze Variable mysql_id für mysql_id

也可以这样使用

mysql_id=sb.toString();

使用不同的变量名(例如,给你的数组命名复数)

【讨论】:

    【解决方案2】:

    ArrayList&lt;String&gt; results = new ArrayList&lt;String&gt;(); 在我看来,结果的类型是 arrayList 而不是字符串。这就是为什么你可以调用它的 add 方法。

    mysql_id 是 string 类型,不支持 add 方法。将其类型更改为 ArrayList

    【讨论】:

      【解决方案3】:

      这里你声明为字符串

      public void getData() {
      Thread t = new Thread() {   //Setzte Tread
      private String result = ""; //Setze Variable String für die Ergebnisse
      private String mysql_id = "";  
      

      其实应该是arraylist

      ArrayList<String> results = new ArrayList<String>();
      ArrayList<String> mysql_id = new ArrayList<String>();
      

      【讨论】:

        【解决方案4】:

        尝试使用 getString() 代替 get():

        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;
        import org.json.JSONTokener;
        ...
        for (int i = 0; i < array.length(); i++) {                                              
           JSONObject obj = array.getJSONObject(i);                                 
           String product= (obj.getString("product"));
           results.add(product);
           ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-05
          • 1970-01-01
          • 1970-01-01
          • 2015-11-20
          相关资源
          最近更新 更多